Skip to main content
Lesson 14 - Inheritance
ZIPPDF (letter)
Lesson MenuPreviousNext
  
Method Overriding page 6 of 10

  1. A derived class can override a method from its base class by defining a replacement method with the same signature. For example in our Student subclass, the toString() method contained in the Person superclass does not reference the new variables that have been added to objects of type Student, so nothing new is printed out. We need a new toString() method in the class Student:

    // overrides the toString method in the parent class
    public String toString()
    {
      return myName + ", age: " + myAge + ", gender: " + myGender +
             ", student id: " + myIdNum + ", gpa: " + myGPA;
    }
  2. Even though the base class has a toString() method, the new definition of toString() in the derived class will override the base class's version . The base class has its method, and the derived class has its own method with the same name. With the change in the Student class the following program will print out the full information for both items.

    class School
    {
      public static void main (String args[])
      {
        Person bob = new Person("Coach Bob", 27, "M");
        Student lynne = new Student("Lynne Brooke", 16, "F",
                                     "HS95129", 3.5);
    
        System.out.println(bob.toString());
        System.out.println(lynne.toString());
      }
    }
    
    Run Output:
    
    Coach Bob, age: 27, gender: M
    Lynne Brooke, age: 16, gender: F, student id: HS95129, gpa: 3.5

    The line bob.toString() calls the toString() method defined in Person, and the line lynne.toString() calls the toString() method defined in Student.

  3. Sometimes (as in the example) you want a derived class to have its own method, but that method includes everything the derived class's method does. You can use the super reference in this situation to first invoke the original toString() method in the base class as follows:

    public String toString()
    {
      return super.toString() +
             ", student id: " + myIdNum + ", gpa: " + myGPA;
    }

    Inside a method, super does not have to be used in the first statement, unlike the case when super is used in a constructor.


Lesson MenuPreviousNext
Contact
 ©ICT 2003, All Rights Reserved.