Pitfall: “overriding” private methods
Here’s something you might innocently try to do:
//: c07:PrivateOverride.java
// Abstract classes and methods.
import com.bruceeckel.simpletest.*;
public class PrivateOverride {
private static Test monitor = new Test();
private void f() {
System.out.println("private f()");
}
public static void main(String[] args) {
PrivateOverride po = new Derived();
po.f();
monitor.expect(new String[] {
"private f()"
});
}
}
class Derived extends PrivateOverride {
public void f() {
System.out.println("public f()");
}
} ///:~
You might reasonably expect the output to be “public f( )”, but a private method is automatically final, and is also hidden from the derived class. So Derived’s f( ) in this case is a brand new method; it’s not even overloaded, since the base-class version of f( ) isn’t visible in Derived.
The result of this is that only non-private methods may be overridden, but you should watch out for the appearance of overriding private methods, which generates no compiler warnings, but doesn’t do what you might expect. To be clear, you should use a different name from a private base-class method in your derived class.