Skip to main content
ICT
Lesson A11 - Inheritance
 
Main Previous Next
Title Page >  
Summary >  
Lesson A1 >  
Lesson A2 >  
Lesson A3 >  
Lesson A4 >  
Lesson A5 >  
Lesson A6 >  
Lesson A7 >  
Lesson A8 >  
Lesson A9 >  
Lesson A10 >  
Lesson A11 >  
Lesson A12 >  
Lesson A13 >  
Lesson A14 >  
Lesson A15 >  
Lesson A16 >  
Lesson A17 >  
Lesson A18 >  
Lesson A19 >  
Lesson A20 >  
Lesson A21 >  
Lesson A22 >  
Lesson AB23 >  
Lesson AB24 >  
Lesson AB25 >  
Lesson AB26 >  
Lesson AB27 >  
Lesson AB28 >  
Lesson AB29 >  
Lesson AB30 >  
Lesson AB31 >  
Lesson AB32 >  
Lesson AB33 >  
Vocabulary >  
 

D. 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 getName() + ", age: " + getAge() + ", gender: "
              + getGender() + ", student id: " + myIdNum
              + ", gpa: " + myGPA;
    }

    A more efficient alternative is to use super to invoke the toString() method from the parent class while adding information unique to the Student subclass:

    public String toString(){
        return super.toString() +
              ", 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.

    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());

The output to this block of code is:

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.

 

Main Previous Next
Contact
 © ICT 2006, All Rights Reserved.