Java Reference
In-Depth Information
definition of the no-argument constructor for the class HourlyEmployee (with super
omitted) is equivalent to the version we gave in Display 7.3:
public HourlyEmployee()
{
wageRate = 0;
hours = 0;
}
A derived class object has all the instance variables of the base class. These inherited
instance variables should be initialized, and the base class constructor is the most conve-
nient place to initialize these inherited instance variables. That is why you should always
include a call to one of the base class constructors when you define a constructor for a
derived class. As already noted, if you do not include a call to a base class constructor
(using super ), then the no-argument constructor of the base class is called automatically.
(If there is no no-argument constructor for the base class, that is an error condition.)
Call to a Base Class Constructor
Within the definition of a constructor for a class, you can use super as a name for a con-
structor of the base class. Any invocation of super must be the first action taken by the
constructor.
EXAMPLE
public SalariedEmployee(SalariedEmployee originalObject)
{
super (originalObject); //Invocation of base class constructor.
salary = originalObject.salary;
}
The this Constructor
When defining a constructor, it is sometimes convenient to be able to call one of the
other constructors in the same class. You can use the keyword this as a method name to
invoke a constructor in the same class. This use of this is similar to the use of super , but
with this , the call is to a constructor of the same class, not to a constructor for the base
class. For example, consider the following alternate, and equivalent, definition of the no-
argument constructor for the class HourlyEmployee (from Display 7.3):
this
public HourlyEmployee()
{
this ("No name", new Date("January", 1, 1000), 0, 0);
}
Search WWH ::




Custom Search