In: Computer Science
Java: modify the given example code to make it possible to create a student object by only specifying the name, all other info may be absent. it may also be possible to add a tag with an absent value. use OPTIONAL TYPE and NULL object design pattern.
import java.util.HashMap; import java.util.Map; public class Student { private final String aName; private String aGender; private int aAge; private Country aCountry; private Map aTags = new HashMap<>(); public Student(String pName) { aName = pName; } public String getName() { return aName; } //getGender, getAge, getCountry, getTag public void editTag(String pTag, String pValue) { aTags.put(pTag, pValue); } }
creating student with name JACK and no gender and age. except name, all fields are optional
Code with comments
Temp.js (driver class)
import java.util.HashMap;
import java.util.Map;
import java.util.Optional;
class Temp {
public static void main(String[] args) {
Student stud = new Student("JACK");
System.out.println(stud.getName());
System.out.println(stud.getGender());
System.out.println(stud.getAge());
}
}
class Country {
}// define your class
class Student {
private final String aName;
private Optional<String> aGender; // optional fields
private Optional<Integer> aAge; // optional fields
private Optional<Country> aCountry; // optional fields
private Optional<Map> aTags; // optional fields
public Student(String pName) {
aName = pName;
aGender = Optional.ofNullable(null); // setting null
aAge = Optional.ofNullable(null); // setting null
aCountry = Optional.ofNullable(null); // setting null
aTags = Optional.of(new HashMap<>()); // initializing with empty map
}
public String getName() {
return aName; // return name
}
// getGender, getAge, getCountry, getTag
public void editTag(String pTag, String pValue) {
aTags.get().put(pTag, pValue);
}
public String getGender() {
return aGender.orElse("Unknown Gender"); // return if present otherwise this parameter
}
public Integer getAge() {
return aAge.orElse(-1);// return if present otherwise this parameter
}
public Country getCountry() {
return aCountry.orElse(null);// return if present otherwise this parameter
}
public Map getTags() {
return aTags.get();
}
}