Java Reference
In-Depth Information
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
GeometricOb-
ject
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 can-
not 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?
Overloading means to define multiple methods with the same name but different signa-
tures. Overriding means to provide a new implementation for a method in the subclass.
Key
Point
You learned about overloading methods in Section 6.8. To override a method, the method
must be defined in the subclass using the same signature and the same return type.
Let us use an example to show the differences between overriding and overloading. In (a)
below, the method
p(double i)
in class
A
overrides the same method defined in class
B
. In
(b), however, the class
A
has two overloaded methods:
p(double i)
and
p(int i)
. The
method
p(double i)
is inherited from
B
.
public class
Test {
public static void
main(String[] args) {
A a =
new
A();
a.p(
10
);
a.p(
10.0
);
}
}
public class
Test {
public static void
main(String[] args) {
A a =
new
A();
a.p(
10
);
a.p(
10.0
);
}
}
class
B {
public void
p(
double
i) {
System.out.println(i *
2
);
}
}
class
B {
public void
p(
double
i) {
System.out.println(i *
2
);
}
}
class
A
extends
B {
// This method
overrides
the method in B
public void
p(
double
i) {
System.out.println(i);
}
}
class
A
extends
B {
// This method
overloads
the method in B
public void
p(
int
i) {
System.out.println(i);
}
}
(a)
(b)
Search WWH ::
Custom Search