Java Reference
In-Depth Information
< Day Day Up >
Puzzle 66: A Private Matter
In this program, a subclass field has the same name as a superclass field. What does the program
print?
class Base {
public String className = "Base";
}
class Derived extends Base {
private String className = "Derived";
}
public class PrivateMatter {
public static void main(String[] args) {
System.out.println(new Derived().className);
}
}
Solution 66: A Private Matter
A superficial analysis of the program might suggest that it should print
Derived
, because that is
what is stored in the
className
field of each
Derived
instance. A deeper analysis suggests that
class
Derived
won't compile, because the variable
className
in
Derived
has more restrictive
access than it does in
Base
: It is declared
private
in
Derived
and
public
in
Base
. If you tried
compiling the program, you found that neither analysis is correct. The program doesn't compile, but
the error is in the class
PrivateMatter
.
Had
className
been an instance method instead of an instance field,
Derived.className()
would
have
overridden
Base.className()
, and the program would have been illegal. The access modifier
of an overriding method must provide at least as much access as that of the overridden method [JLS
Search WWH ::
Custom Search