Java Reference
In-Depth Information
Display 7.8
Use of the
EnhancedStringTokenizer
Class
(part 2 of 2)
Sample Dialogue
Enter a sentence:
I love you, madly.
Your sentence with extra blanks deleted:
I love you, madly.
Sentence with each word on a separate line:
I
love
you,
madly.
7.2
Encapsulation and Inheritance
Ignorance is bliss.
PROVERB
This section is a continuation of Section 7.1 and uses the same example classes we
used in Section 7.1. In this section, we consider how the information-hiding facilities
of Java, primarily the
private
modifier, interact with inheritance.
PITFALL: Use of Private Instance Variables from the Base Class
An object of the class
HourlyEmployee
(Display 7.3) inherits, among other things, an
instance variable called
name
from the class
Employee
(Display 7.2). For example, the fol-
lowing would set the value of the instance variable
name
of the
HourlyEmployee
object
joe
to
"Josephine"
:
joe.setName("Josephine");
But you must be a bit careful about how you manipulate inherited instance variables
such as
name
. The instance variable
name
of the class
HourlyEmployee
was inherited from
the class
Employee
, but the instance variable
name
is a private instance variable in the def-
inition of the class
Employee
. That means that
name
can only be accessed by name within
the definition of a method in the class
Employee
. An instance variable (or method) that is
private in a base class is not accessible
by name
in the definition of a method in
any other
class, not even in a method definition of a derived class.
For example, notice the following method definition taken from the definition of the
class
HourlyEmployee
in Display 7.3: