Java Reference
In-Depth Information
PITFALL: The Terms
Subclass
and
Superclass
Many programmers and authors use the term
subclass
for a derived class and
superclass
for its base class (or any of its ancestor classes). This is logical. For example, the collection of
all hourly employees in the world is a subclass of all employees. Similarly, the collection of all
objects of type
HourlyEmployee
is a subcollection of the collection of all objects of the class
Employee
. As you add more instance variables and methods, you restrict the number of
objects that can satisfy the class definition. Despite this logic, people often reverse the terms
subclass
and
superclass.
Remember that these terms refer to the collections of objects of the
derived class and the base class and not to the number of instance variables or methods. A
derived class is a
subclass
(
not a superclass
) of its base class. Another way to remember
which is a superclass is as follows: Recall that the
super
constructor invocation is an invoca-
tion of the base class and so the base class is the
superclass
.
subclass and
superclass
■
Self-Test Exercises
5. Is the following program legal? The relevant classes are defined in Displays 7.2,
7.3, and 7.5.
public class
EmployeeDemo
{
public static void main( String[] args)
{
HourlyEmployee joe =
new
HourlyEmployee("Joe Young",
new
Date("February", 1, 2004), 10.50, 40);
SalariedEmployee boss =
new
SalariedEmployee("Mr. Big Shot",
new
Date("January", 1, 1999), 100000);
printName(joe);
printName(boss);
}
public void
printName(Employee object)
{
System.out.println(object.getName());
}
}
6. Give a definition for a class
TitledEmployee
that is a derived class of the base class
SalariedEmployee
given in Display 7.5. The class
TitledEmployee
has one addi-
tional instance variable of type
String
called
title
. It also has two additional meth-
ods:
getTitle
, which takes no arguments and returns a
String
, and
setTitle
,
which is a
void
method that takes one argument of type
String
. It also overrides
(redefines) the method definition for
getName
, so that the string returned includes
the title as well as the name of the employee.