Java Reference
In-Depth Information
You could rewrite the
printCircle()
method in the
Circle
class as follows:
public void
printCircle() {
System.out.println(
"The circle is created "
+
super
.getDateCreated() +
" and the radius is "
+ radius);
}
It is not necessary to put
super
before
getDateCreated()
in this case, however, because
getDateCreated
is a method in the
GeometricObject
class and is inherited by the
Circle
class. Nevertheless, in some cases, as shown in the next section, the keyword
super
is needed.
11.4
What is the output of running the class
C
in (a)? What problem arises in compiling the
program in (b)?
✓
✓
Check
Point
class
A {
public
A() {
System.out.println(
"A's no-arg constructor is invoked"
);
class
A {
public
A(
int
x) {
}
}
}
}
class
B
extends
A {
public
B() {
}
}
class
B
extends
A {
}
public
class C {
public static void
main(String[] args) {
B b =
new
B();
}
}
public class
C {
public static void
main(String[] args) {
B b =
new
B();
}
}
(a)
(b)
11.5
How does a subclass invoke its superclass's constructor?
11.6
True or false? When invoking a constructor from a subclass, its superclass's no-arg
constructor is always invoked.
To override a method, the method must be defined in the subclass using the same sig-
nature 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 }
Search WWH ::
Custom Search