Java Reference
In-Depth Information
Running the example again produces the following output:
This is a Dog
It's Fido the Chihuahua
This is a Dog
It's Lassie the Unknown
How It Works
You use the
super
keyword to identify the base class version of
toString()
that is hidden by the derived
class version. You used the same notation to refer to superclass data members that were hidden by de-
rived class data members with the same name. Calling the base class version of
toString()
returns the
String
object for the base part of the object. You then append extra information to this about the derived
part of the object to produce a
String
object specific to the derived class.
THE @Override ANNOTATION
When you define a method in a derived class that is intended to override a superclass method, it is easy to
make a mistake in the signature for the derived class method. If the name and parameter list of your derived
class method are not identical to that of the superclass method, you are defining an
overload
for the base
class method, not an
override
.
The
@Override
annotation is intended to protect you from this kind of error. Here's how you could use
the
@Override
annotation in the
Dog
class:
public class Dog extends Animal {
public Dog(String aName) {
super("Dog"); // Call the base constructor
name = aName; // Supplied name
breed = "Unknown"; // Default breed value
}
public Dog(String aName, String aBreed) {
super("Dog"); // Call the base constructor
name = aName; // Supplied name
breed = aBreed; // Supplied breed
}
// Present a dog's details as a string
@Override
public String toString() {
return super.toString() + "\nIt's " + name + " the " + breed;
}
protected String name; // Name of a Dog
protected String breed; // Dog breed
}
Obviously you are unlikely to make an error in the parameter list for the
toString()
method that is in-
herited from the
Object
class. However, you might spell the name as
ToString()
, in which case you do not
have an override for
toString()
; you have just added a new method.