Java Reference
In-Depth Information
// Call the setErrorMsg function in the base class ErrorMsg.
super.setErrorMsg (inputMsg);
if (msgSize != 0) {
linesToSkip = 1;
}
}
}
S
HARING
V
ARIABLES AND
M
ETHODS
When a class derives from another class, it inherits all of the class data members and
methods from its base classes if the scope of those data members is not private. This
means that all of the variables and methods defined in the base classes are available in
the derived classes. For example, look carefully at the statement in
PrintfileErrorMsg
that sets
linesToSkip
:
if (msgSize != 0) {
linesToSkip = 1;
}
Where did the variable
msgSize
come from?
PrintfileErrorMsg
did not explicitly
define this variable. The only one defined is in
TextMessage
, which
ErrorMsg
inherits.
But remember,
PrintfileErrorMsg
inherits from
ErrorMsg
(which inherits from
TextMessage
). Therefore,
ErrorMsg
,
PrintfileErrorMsg
, and
TextMessage
all share
the variables defined in
TextMessage
.
Any of the class instances in this hierarchy can treat
msgSize
as if it is contained
in this class instance. At the same time, if any of these class instances modifies
msg-
Size
, then all of the class instances will see this modification. How does this work?
When an instance of
PrintfileErrorMsg
is created, it automatically creates an in-
stance of
ErrorMsg
, which automatically creates an instance of
TextMessage
. The
variable
msgSize
is created when
TextMessage
is created, and all of these instances
share this single copy of the variable
msgSize
.
H
IDING
V
ARIABLES AND
M
ETHODS
A derived class
can
create its own copies of base class variables or methods. To un-
derstand this better, let's examine how variable declarations (class data members)
are handled.