Java Reference
In-Depth Information
Java syntax: Subclass definition
public class
subclass-name
extends
superclass-name
{
declarations of methods and fields
}
Purpose
: To define a new file drawer, named
subclass-name
, and
describe the contents of its manila folders (instances of the class). They
have the methods and fields that are declared in superclass
superclass-
name
as well as the methods and fields being declared in the subclass.
Actually, the subclass is not new to you. It was discussed in some detail in
Sec.1.4, and you have already learned that the subclass is a mechanism for cus-
tomizing a class to fit new needs. An instance of the subclass has all the compo-
nents (instance variables and instance methods) that the superclass does, but it
can define new ones. In Sec. 1.4, we also showed how to draw an instance of a
subclass (see Fig. 1.9). In this chapter, we review the concepts discussed in
Sec.1.4 and go into more detail on some of the issues concerning subclasses.
4.1
The subclass definition
Figure 4.1 contains a definition of a class
Executive
. Because of the
extends
clause
Get class Em-
ployee and its
subclasses
from a footnote
on lesson page
4-1 of the CD.
extends
Employee
in the first line, class
Executive
is called a
subclass
of class
Employee
and class
Employee
is called a
superclass
of
Executive
. The presence of this clause
means that every instance component of class
Employee
is also an instance com-
ponent of class
Executive
. We say that
Executive
inherits
the instance vari-
ables and methods of
Employee
. But subclass
Executive
can have additional
instance components.
Figure 4.1 contains uses of keyword
super
in the constructor and functions
toString
and
getCompensation
. Keyword
super
is explained in subsections
4.1.1 and 4.1.3.
Figure 4.2 shows how we draw an instance of subclass
Executive
. The
folder has two partitions. At the top is the partition for components that are inher-
ited from class
Employee
; the name
Employee
is in a box in the upper righthand
corner of the partition. At the bottom is the partition for components that are
defined in the subclass,
Executive
; the name of the subclass is in a box in the
upper righthand corner of the partition.
We draw every instance of a subclass in this fashion. Having a standard way
to draw such manila folders makes it easier to communicate.
Subclass
Executive
contains a private field,
bonus
. Since only
Execu-
tives
, and not other
Employees
, get bonuses, this field is placed in the subclass.
Superclass
Employee
contains only fields that represent properties that all
employees have.
Activities 4-1.2
and 4-1.3 dis-
cuss subclasses
with a slight
variation of
Employee and
its subclasses.
Search WWH ::
Custom Search