Java Reference
In-Depth Information
23
public
Person() {
24 System.out.println(
"(1) Performs Person's tasks"
);
25 }
26 }
(1) Performs Person's tasks
(2) Invoke Employee's overloaded constructor
(3) Performs Employee's tasks
(4) Performs Faculty's tasks
The program produces the preceding output. Why? Let us discuss the reason. In line 3,
new Faculty()
invokes
Faculty
's no-arg constructor. Since
Faculty
is a subclass of
Employee
,
Employee
's no-arg constructor is invoked before any statements in
Faculty
's
constructor are executed.
Employee
's no-arg constructor invokes
Employee
's second con-
structor (line 13). Since
Employee
is a subclass of
Person
,
Person
's no-arg constructor is
invoked before any statements in
Employee
's second constructor are executed. This process
is illustrated in the following figure.
Faculty() {
Employee() {
this
(
"(2) ..."
);
Employee(String s) {
Person() {
Performs Faculty's
tasks;
Performs Employee's
tasks;
Performs Employee's
tasks;
Performs Person's
tasks;
}
}
}
}
Caution
If a class is designed to be extended, it is better to provide a no-arg constructor to avoid
programming errors. Consider the following code:
no-arg constructor
1
public class
Apple
extends
Fruit {
2 }
3
4
class
Fruit {
5
public
Fruit(String name) {
6 System.out.println(
"Fruit's constructor is invoked"
);
7 }
8 }
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);
Search WWH ::
Custom Search