next up previous
Next: Compatibility between actual and Up: Unit 08 Previous: Inherited methods and variables

Compatibility

We have said that each object of the derived class is also an object of the base class. This implies that it is possible to use an object of the derived class in each situation or context in which it is possible to use an object of the base class. In other words, the objects of the derived class are compatible with the objects of the base class.

But the contrary is not true! Consider the following program.

public class TestCompatibility {
  public static void main(String[] args) {
    Person p = new Person("Daniele", "Roma");
    Student s = new Student("Jacopo", "Roma", "Engineering");
    Person pp;
    Student ss;
    pp = s;    //OK! Student is compatible with Person
    ss = p;    //ERROR! Person is not compatible with Student
    System.out.println(pp.getName());
               //OK! getName() is a method of Person
    System.out.println(pp.getResidence());
               //OK! getResidence is a method of Person
    System.out.println(pp.getFaculty());
               //ERROR! getFaculty is not a method of Person
  }
}

Note: The error in the last statement is due to the fact that the variable pp is a reference to a Person, and hence, through this variable it is not possible to access the methods of Student (even if in this case pp actually refers to an object Student). This is because Java implements static type checking.


next up previous
Next: Compatibility between actual and Up: Unit 08 Previous: Inherited methods and variables