Java Reference
In-Depth Information
// Present a dog's details as a string
public String toString() {
return "It's " + name + " the " + breed;
}
With this change to the example, the output is now:
It's Fido the Chihuahua
It's Lassie the Unknown
How It Works
The
toString()
method in the
Dog
class overrides the base class method because it has the same signa-
ture. Recall from Chapter 5 that the signature of a method is determined by its name and the parameter
list. So, now whenever you use the
toString()
method for a
Dog
object either explicitly or implicitly,
this method is called — not the base class method.
NOTE
You are obliged to declare the
toString()
method as
public
.
When you
override a base class method, you cannot change the access attributes of the new
version of the method to be more stringent than that of the base class method that it
overrides. Because
public
is the least stringent access attribute, you have no other
choice.
Of course, ideally you would like to output the member,
type
, of the base class, but you can't reference
this in the derived class because it is not inherited. However, you can still call the base class version of
toString()
. It's another job for the
super
keyword.
TRY IT OUT: Calling a Base Class Method from a Derived
Class
You can rewrite the derived class version of
toString()
to call the base method:
// Present a dog's details as a string
public String toString() {
return super.toString() + "\nIt's " + name + " the " + breed;
}
Directory "TestDerived"