In: Computer Science
How do you write the constructor for the three private fields? public class Student implements Named { private Person asPerson; private String major; private String universityName; @Override public String name() { return asPerson.name(); }
The constructor can be written as follows. The comments are provided for the better understanding of the logic.
public class Student implements Named {
private Person asPerson;
private String major;
private String universityName;
//The constructor can be written as follows
//There should be 3 paramters one each representing the private variable
public Student(Person asPerson, String major, String universityName) {
//In the below lines of code "this.asPerson" points to the class level private variable
//The variable "asPerson" points to the incoming paramter.
this.asPerson = asPerson;
this.major = major;
this.universityName = universityName;
}
@Override
public String name() {
return asPerson.name();
}
}
The screenshots of the code is provided below.