Java Reference
In-Depth Information
12. public Employee(String fn, String ln, Date hd) {
13. System.out.println(“Inside second constructor”);
14. firstName = fn;
15. lastName = ln;
16. hireDate = hd;
17. }
18.}
Notice how there is no repetition of code in the constructors. Study this Employee class
and try to determine the output of the following statement:
Employee e = new Employee(“Beetle”, “Bailey”);
This statement results in the following sequence of events:
1. The Employee constructor on line 7 is invoked because we are passing in two String
objects.
2. Line 8 invokes the constructor on line 12.
3. This second constructor actually executes first, and when it is finished, control jumps
back to line 9.
Therefore, the output of instantiating this new “Beetle Bailey” Employee is
Inside second constructor
Inside first constructor
Invoking Another Constructor Using this
The call to this must be the fi rst line of code in the constructor or a compiler error
occurs. For example, the following Employee constructor does not compile:
public Employee(String fn, String ln) {
System.out.println(“Inside first constructor”);
this(fn, ln, new Date());
}
The compiler generates the following error:
Employee.java:9: call to this must be first statement in constructor
this(fn, ln, new Date());
^
We will revisit this rule in the next section on using the super keyword in constructors.
Search WWH ::




Custom Search