Java Reference
In-Depth Information
Since no constructor is explicitly defined in
Apple
,
Apple
's default no-arg constructor
is defined implicitly. Since
Apple
is a subclass of
Fruit
,
Apple
's default constructor
automatically invokes
Fruit
's no-arg constructor. However,
Fruit
does not have a
no-arg constructor, because
Fruit
has an explicit constructor defined. Therefore, the
program cannot be compiled.
Design Guide
If possible, you should provide a no-arg constructor for every class to make the class
easy to extend and to avoid errors.
no-arg constructor
11.3.3 Calling Superclass Methods
The keyword
super
can also be used to reference a method other than the constructor in the
superclass. The syntax is:
super
.method(parameters);
You could rewrite the
printCircle()
method in the
Circle
class as follows:
public void
printCircle() {
System.out.println(
"The circle is created "
+
getDateCreated() +
" and the radius is "
+ radius);
super
.
}
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 printout 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.