Java Reference
In-Depth Information
7 System.out.println(
"(4) Performs Faculty's tasks"
);
8 }
9 }
10
11
class
Employee
extends
Person
{
12 {
13
this
(
"(2) Invoke Employee's overloaded constructor"
);
14 System.out.println(
"(3) Performs Employee's tasks "
);
15 }
16
17
public
Employee()
invoke overloaded
constructor
public
Employee(String s)
{
18 System.out.println(s);
19 }
20 }
21
22
class
Person {
23 {
24 System.out.println(
"(1) Performs Person's tasks"
);
25 }
26 }
public
Person()
(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 12). 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
{
5
public
Fruit(String name) {
6 System.out.println(
"Fruit's constructor is invoked"
);
7 }
8 }
Fruit