Java Reference
In-Depth Information
/** Constructor: person with name n , hired this year, salary 50,000 */
public Employee(String n) {
name= n;
start= ( new Date()).getYear() + 1900;
}
(The year is obtained using an instance of class Date of package java.util , so
we need to import classes of this package. First, an instance of Date is created;
then its function getYear is called, which yields the number of years assuming
1900 as year 0 ; finally 1900 is added to this value.)
Writing more than one constructor takes time and effort, but it will save time
and effort in using the class and is well worth it. Having several constructors can
make the user's task easier.
Calling or invoking one constructor from another
Class Employee of Fig. 3.1 contains a constructor that initializes fields name
and start . In the body of the second constructor, shown above, instead of ini-
tializing the fields directly, we would like to call the first constructor. At first
glance, it would seem that we could replace the two statements in the body of the
above function with one constructor call:
Activity
3-5.4
Employee(n, ( new Date()).getYear() + 1900);
However, this is not the syntax that Java uses to call one constructor from anoth-
er. The syntax uses keyword this instead of the constructor name:
this (n, ( new Date()).getYear() + 1900);
Note that there is no period following keyword this .
Thus, we write the second constructor as follows:
/** Constructor: person with name n , hired this year,
salary 50,000 */
public Employee(String n) {
this (n, ( new Date()).getYear() + 1900);
}
Only the first statement of a constructor body can call another constructor.
3.1.4
Function toString
A Java convention is to define instance function toString() in each class, as we
did in class Employee of Fig. 3.1. The purpose of function toString is to create
a String description of the instance in which the function appears. Generally,
though not always, the result will contain the values of all the fields of the
instance. In class Employee , toString yields a String that contains the name
and year of hire, but not the salary.
Activity
3-7.2
Search WWH ::




Custom Search