Java Reference
In-Depth Information
public static void main(String[] args) {
ExtendShow ext = new ExtendShow();
SuperShow sup = ext;
sup.show();
ext.show();
System.out.println("sup.str = " + sup.str);
System.out.println("ext.str = " + ext.str);
}
}
There is only one object, but we have two variables containing referen-
ces to it: One variable has type
SuperShow
(the superclass) and the other
variable has type
ExtendedShow
(the actual class). Here is the output of
the example when run:
Extend.show: ExtendStr
Extend.show: ExtendStr
sup.str = SuperStr
ext.str = ExtendStr
For the
show
method, the behavior is as you expect: The actual class
of the object, not the type of the reference, governs which version of
the method is called. When you have an
ExtendShow
object, invoking
show
always calls
ExtendShow
's
show
even if you access it through a reference
declared with the type
SuperShow
. This occurs whether
show
is invoked ex-
ternally (as in the example) or internally within another method of either
ExtendShow
or
SuperShow
.
For the
str
field, the type of the
reference,
not the actual class of the
ob-
ject,
determines which class's field is accessed. In fact, each
ExtendShow
object has
two
String
fields, both called
str
, one of which is hidden by
ExtendShow
's own, different field called
str
: