Java Reference
In-Depth Information
If you want the program to print Derived — that is, you want it to exhibit overriding behavior— use
public methods in place of public fields. This is, in any case, a good idea because it provides better
encapsulation [EJ Item 19]. The following version of the program uses this technique and prints
Derived as expected:
class Base {
public String getClassName() {
return "Base";
}
}
class Derived extends Base {
public String getClassName() {
return "Derived";
}
}
public class PublicMatter {
public static void main(String[] args) {
System.out.println(new Derived().getClassName());
}
}
Note that we declared the method getClassName to be public in class Derived even though the
corresponding field was private in the original program. As mentioned previously, an overriding
method must have an access modifier that is no less restrictive than the method it overrides.
The lesson of this puzzle is that hiding is generally a bad idea. The language allows you to hide
variables, nested types, and even static methods (as in Puzzle 48), but just because you can doesn't
mean that you should. The problem with hiding is that it leads to confusion in the mind of the
reader. Are you using the hidden entity or the entity that is doing the hiding? To avoid this
 
 
Search WWH ::




Custom Search