Java Reference
In-Depth Information
The field that gets accessed is determined at compile time based on the
type of the reference used to access it.
Inside a method, such as show , a reference to a field always refers to the
field declared in the class in which the method is declared, or else to an
inherited field if there is no declaration in that class. So in SuperShow.show
the reference to str is to SuperShow.str , whereas in ExtendShow.show the
reference to str is to ExtendShow.str .
You've already seen that method overriding enables you to extend exist-
ing code by reusing it with objects of expanded, specialized functionality
not foreseen by the inventor of the original code. But where fields are
concerned, it is hard to think of cases in which hiding them is a useful
feature.
If an existing method had a parameter of type SuperShow and accessed
str with that object's reference, it would always get SuperShow.str even
if the method were actually handed an object of type ExtendShow . If the
classes were designed to use a method instead of a field to access the
string, the overriding method would be invoked in such a case and the
ExtendShow.str could be returned. This hiding behavior is often anoth-
er reason to prefer defining classes with private data accessed only by
methods, which are overridden, not hidden.
Hiding fields is allowed because implementors of existing superclasses
must be free to add new public or protected fields without breaking sub-
classes. If the language forbade using the same field name in a super-
class and a subclass, adding a new field to an existing superclass could
potentially break any subclasses already using those names.
 
Search WWH ::




Custom Search