Java Reference
In-Depth Information
Here, Y is now derived from X ; thus, it is permissible for x2 to be assigned a reference to
a Y object.
It is important to understand that it is the type of the reference variable—not the type of
the object that it refers to—that determines what members can be accessed. That is, when a
reference to a subclass object is assigned to a superclass reference variable, you will have
access only to those parts of the object defined by the superclass. This is why x2 can't ac-
cess b even when it refers to a Y object. If you think about it, this makes sense, because the
superclass has no knowledge of what a subclass adds to it. This is why the last line of code
in the program is commented out.
Although the preceding discussion may seem a bit esoteric, it has some important prac-
tical applications. One is described here. The other is discussed later in this chapter, when
method overriding is covered.
An important place where subclass references are assigned to superclass variables is
when constructors are called in a class hierarchy. As you know, it is common for a class to
define a constructor that takes an object of the class as a parameter. This allows the class to
construct a copy of an object. Subclasses of such a class can take advantage of this feature.
For example, consider the following versions of TwoDShape and Triangle . Both add con-
structors that take an object as a parameter.
Search WWH ::




Custom Search