Java Reference
In-Depth Information
Figure 6.3
The overridden toString() method in the Radio class is invoked.
Now when toString() is invoked on a Radio object, the toString() method in
the Radio class will be invoked, not the toString() method in the Object class.
The toString() method in the Object class is essentially hidden for Radio objects,
which is the result we wanted.
Let's run the ToStringDemo program again, this time using our new Radio
class. Try to determine how the output will change. Figure 6.3 shows the output.
The toString() method in the Radio class of Figure 6.3 demonstrates a
child class that wanted to completely change the behavior of an inherited
method, in this case, toString() from Object. There are times when a child
class might want to add to the behavior of an inherited method and not
completely replace the parent method. A child class can use the super
keyword to invoke the overridden method in the parent. The details of
using super are discussed next.
The super Keyword
Every object has a reference to itself called the this reference, and there are sit-
uations where a class needs to explicitly use the this reference when referring
to its fields or methods. Similarly, a class can use the super keyword to explic-
itly refer to a field or method that is inherited from a parent. You can think of
super as a child object's reference to its parent object.
To demonstrate using super, the following Employee class explicitly uses
the super keyword to invoke the toString() method inherited from Object.
(Notice that the Employee class also explicitly uses the this reference to access
its fields name and address, although it is not necessary in this particular
instance.)
public class Employee
{
public String name;
public String address;
public int SSN;
public int number;
Search WWH ::




Custom Search