Java Reference
In-Depth Information
8.4.8.3]. Because
className
is a field,
Derived.className
hides
Base.className
rather than
overriding it [JLS 8.3]. It is legal, though inadvisable, for one field to hide another when the hiding
field has an access modifier that provides less access than the hidden field. In fact, it is legal for a
hiding field to have a type that is completely unrelated to that of the field it hides: The
Derived
class would be legal even if
Derived.className
were of type
GregorianCalendar
.
The compilation error in our program occurs when class
PrivateMatter
TRies to access
Derived.className
. Although
Base
has a public field
className
, this field is not inherited into
Derived
because it is hidden by
Derived.className
. Within the class
Derived
, the field name
className
refers to the private field
Derived.className
. Because this field is declared
private
, it
is not accessible to the class
PrivateMatter
. Therefore, the compiler generates an error message
something like this:
PrivateMatter.java:11: className has private access in Derived
System.out.println(new Derived().className);
^
Note that it is possible to access the public field
Base.className
in a
Derived
instance even
though it is hidden, by casting the
Derived
instance to
Base
. The following version of
PrivateMatter
prints
Base
:
public class PrivateMatter {
public static void main(String[] args) {
System.out.println((
(Base)
new Derived()).className);
}
}
This demonstrates a big difference between overriding and hiding. Once a method is overridden in a
subclass, you can't invoke it on an instance of the subclass (except from within the subclass, by
using the
super
keyword). You can, however, access a hidden field by casting the subclass instance
to a superclass in which the field is not hidden.
Search WWH ::
Custom Search