Java Reference
In-Depth Information
How It Works
Here, we create two Dog objects, and then output information about them using the println()
method. This will implicitly call the toString() method for each. You could try commenting out the
call to super() in the constructors of the derived class to see the effect of the compiler's efforts to call
the default base class constructor.
We have called the inherited method toString() successfully, but this only knows about the base
class data members. At least we know that the private member, type , is being set up properly. What
we really need though, is a version of toString() for the derived class.
Overriding a Base Class Method
You can define a method in a derived class that has the same signature as a method in the base class. The
access attribute for the method in the derived class can be the same as that in the base class or less restrictive,
but it cannot be more restrictive. This means that if a method is declared as public , in the base class for
example, any derived class definition of the method must also be declared as public . You cannot omit the
access attribute in the derived class in this case, or specify it as private or protected .
When you define a new version of a base class method in this way, the derived class method will be
called for a derived class object, not the method inherited from the base class. The method in the
derived class overrides the method in the base class. The base class method is still there though, and it is
still possible to call it in a derived class. Let's see an overriding method in a derived class in action.
Try It Out - Overriding a Base Class Method
We can add the definition of a new version of toString() to the definition of the derived class, Dog :
// 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 will now be:
It's Fido the Chihuahua
It's Lassie the Unknown
How It Works
This method overrides the base class method because it has the same signature. You will recall from the
last chapter 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
will be called - not the base class method.
Note that 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. Since
public is the least stringent access attribute, you have no other choice.
Search WWH ::




Custom Search