public class Override_private_pitfall { private void f() { /** * Exception : java.lang.StackOverflowError */ Override_private_pitfall.main(new String[]{}); System.out.println("private f();"); } public static void main(String[] args) { Override_private_pitfall opp = new Detial(); /** *error: The method f1() is undefined for the type Override_private_pitfall */ opp.f1(); Detial detial = (Detial)opp; /** * output: public f(); */ detial.f(); /** * output: public f1(); */ detial.f1(); /** * output : private f(); */ opp.f(); }}class Detial extends Override_private_pitfall { public void f1() { System.out.println("public f1();"); } public void f() { System.out.println("public f();"); }}
动态绑定陷阱:
private 方法隐式是final的;不能重载;static和final的方法不会动态绑定,或者说运行时绑定;
so Detial's f() in this case is a brand new method; it's not even overload, since the base-class version of f() isn't visible in Detial.
to be clear you should use a different name from a prative base-class method in your dervied class.