Java Reference
In-Depth Information
Variable declaration statements that are at the beginning of a derived class de-
finition and that are named the same as variables in a base class will cause a new
variable to be created. These new variables will hide the base class variables from
classes that use the derived class (i.e., create an object of this class type) or that de-
rive from it. Identically named variables from the base classes will not be available
to consumers of this derived class.
For example, if ErrorMsg declared its own version of msgSize , then Print-
fileErrorMsg would only be able to “see” this version of msgSize . The copy of msg-
Size declared in TextMessage would not be available to PrintfileErrorMsg . Only the
class that hides a variable can see both versions of the variable. For example, Error-
Msg can reference both its version of msgSize and the copy of msgSize declared in
TextMessage by using the super. reference variable:
if (super.msgSize != 0) {
msgSize = 1;
}
T HE THIS V ARIABLE
Sometimes it is a bit unclear which variable, or method, the programmer intends to
reference in a class. This ambiguity is especially true of derived classes, which nat-
urally share names.
To clarify which variable to use, the operator this can be used. this means “the
members or methods associated with this instance of the class.” The qualifier this is
a sort of generic reference variable automatically created for each object. The as-
signment of msgSize in the previous ErrorMsg example could be expressed as follows:
if (this.msgSize != 0) {
this.linesToSkip = 1;
}
this.linesToSkip specifies the linesToSkip variable that is part of this instance
of the PrintfileErrorMsg class (i.e., the object pointed to by myPrintfile ). ErrorMsg
could use the this syntax to reference the two different copies of msgSize it has ac-
cess to, as follows:
if (super.msgSize != 0) {
this.msgSize = 1;
}
Search WWH ::




Custom Search