Java Reference
In-Depth Information
For example, the following Employee class has two constructors that perform similar
tasks. Line 10 sets the hireDate fi eld to the current date, while line 16 sets hireDate to a
supplied Date . Otherwise, the two constructors are identical.
1. import java.util.Date;
2.
3. public class Employee {
4. private String firstName, lastName;
5. private Date hireDate;
6.
7. public Employee(String fn, String ln) {
8. firstName = fn;
9. lastName = ln;
10. hireDate = new Date();
11. }
12.
13. public Employee(String fn, String ln, Date hd) {
14. firstName = fn;
15. lastName = ln;
16. hireDate = hd;
17. }
18.}
There are many good reasons to avoid repeating code like these two Employee
constructors do. It would be nice if we could pass the arguments from one constructor
to another and perform all the necessary initialization in one place. By using the this
keyword, we can invoke another constructor in the same class. You use this like a method
call, passing in the arguments to the other constructor.
Let's look at an example that fi xes our issue of repeated code in the Employee class. The
following modifi cation has one Employee constructor invoking the other constructor:
1. import java.util.Date;
2.
3. public class Employee {
4. private String firstName, lastName;
5. private Date hireDate;
6.
7. public Employee(String fn, String ln) {
8. this(fn, ln, new Date());
9. System.out.println(“Inside first constructor”);
10. }
11.
Search WWH ::




Custom Search