Next: Inheritance or composition? (optional)
Up: Unit 08
Previous: The class Object
Let us define a class Student2 with functionalities analogous to
Student, but which does not make use of inheritance. The idea is to
include in Student2 an instance variable that is a reference to an
object Person. Such an instance variable is used to maintain the name
and residence properties, and we add to it an instance variable
faculty, used to store the faculty.
public class Student2 {
private Person person;
private String faculty;
public Student2(String name, String residence, String faculty) {
person = new Person(name, residence);
this.faculty = faculty;
}
public String getName() {
return person.getName();
}
public String getResidence() {
return person.getResidence();
}
public void setResidence(String residence) {
person.setResidence(residence);
}
public String getFaculty() {
return faculty;
}
}
Note:
- The class Student2 uses an instance variable Person;
the object Person stores name and residence of the student. Note
that Student2 is a client of Person, hence the field
Person is manipulated using the public methods of the class
Person.
- The class Student2 hides completely from its clients the use of
the object Person. Indeed, it offers its clients the methods
getName(), getResidence(), and setResidence(),
that operate on Student2 objects.
- The class Student2 offers its clients the same operations
(methods) as the class Student. However, the objects
Student2 are not compatible with the objects of the class
Person. Hence, if a variable or a formal parameter is of type
(reference to an object) Person, it cannot contain (a reference to)
an object Student2.
Next: Inheritance or composition? (optional)
Up: Unit 08
Previous: The class Object