Java Reference
In-Depth Information
11.4 Overriding Methods
To override a method, the method must be defined in the subclass using the same
signature and the same return type as in its superclass.
Key
Point
A subclass inherits methods from a superclass. Sometimes it is necessary for the subclass to
modify the implementation of a method defined in the superclass. This is referred to as
method overriding .
The toString method in the GeometricObject class (lines 46-49 in Listing 11.1)
returns the string representation of a geometric object. This method can be overridden to
return the string representation of a circle. To override it, add the following new method in
the Circle class in Listing 11.2.
method overriding
1 public class CircleFromSimpleGeometricObject
2
extends SimpleGeometricObject {
3
// Other methods are omitted
4
5
// Override the toString method defined in the superclass
6
public String toString() {
toString in superclass
7
return
super .toString()
+ "\nradius is " + radius;
8 }
9 }
The toString() method is defined in the GeometricObject class and modified in the
Circle class. Both methods can be used in the Circle class. To invoke the toString
method defined in the GeometricObject class from the Circle class, use
super.toString() (line 7).
Can a subclass of Circle access the toString method defined in the
GeometricObject class using syntax such as super.super.toString() ? No. This is a
syntax error.
Several points are worth noting:
no super.super.methodName()
An instance method can be overridden only if it is accessible. Thus a private method
cannot be overridden, because it is not accessible outside its own class. If a method
defined in a subclass is private in its superclass, the two methods are completely
unrelated.
override accessible instance
method
Like an instance method, a static method can be inherited. However, a static method
cannot be overridden. If a static method defined in the superclass is redefined in a
subclass, the method defined in the superclass is hidden. The hidden static methods
can be invoked using the syntax SuperClassName.staticMethodName .
cannot override static method
11.7
True or false? You can override a private method defined in a superclass.
Check
11.8
Point
True or false? You can override a static method defined in a superclass.
11.9
How do you explicitly invoke a superclass's constructor from a subclass?
11.10
How do you invoke an overridden superclass method from a subclass?
11.5 Overriding vs. Overloading
Overloading means to define multiple methods with the same name but different
signatures. Overriding means to provide a new implementation for a method in the
subclass.
Key
Point
You learned about overloading methods in Section 5.8. To override a method, the method
must be defined in the subclass using the same signature and the same return type.
 
 
 
 
Search WWH ::




Custom Search