next up previous
Next: Polymorphism Up: Unit 08 Previous: Overriding of methods

Overriding of methods: example

Assume that in Person we define a method printData() as follows:

public class Person {
  ...
  public void printData() {
    System.out.println(name + "  " + residence);
  }
  ...
}

We do overriding of the method printData() in the class Student, in such a way that printData() prints also the faculty:

public class Student extends Person {
  ...
  public void printData() { // overriding of printData of Person!!!
    System.out.println(this.getName() + "  " + this.getResidence() + "  "
                       + faculty);
  }
  ...
}

An example of client is the following.

public class ClientStudent {
   public static void main(String[] args) {
     Person p = new Person("Daniele", "Roma");
     Student s = new Student("Jacopo", "Roma", "Engineering");
     p.printData();
     s.printData();
   }
}


next up previous
Next: Polymorphism Up: Unit 08 Previous: Overriding of methods