- 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;
}
- 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
.