next up previous
Next: Inheritance or composition? (optional) Up: Unit 08 Previous: The class Object

Composition (optional)

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:


next up previous
Next: Inheritance or composition? (optional) Up: Unit 08 Previous: The class Object