pitfall override private method

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();");
 }
}

動態綁定陷阱: java

private 方法隱式是final的;不能重載;static和final的方法不會動態綁定,或者說運行時綁定; ide

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. this

to be clear you should use a different name from a prative base-class method in your dervied class. code

相關文章
相關標籤/搜索