我已經在Stack Overflow上看到了有關我的問題的答案,但我仍然留有一些含糊之處。父類方法可以訪問自己的私有實例變量。如果子類繼承該類,那麼在Child
類的實例上調用getA()
方法時會發生什麼?它是否返回Parent
類中的a
類或Child
類中的a
?在子類中訪問私有實例
class Parent {
private int a = 10;
public int getA() {
return a;
}
}
class Child extends Parent {
private int a = 22;
}
public class Test {
public static void main(String []args) throws Exception {
Child c = new Child();
System.out.println(c.getA());
}
}
我知道它藏起來了,那不是我想要的 – 2015-04-01 06:19:36
@KishoreKumarKorada那麼你想要什麼? – immibis 2015-04-01 06:22:02
我知道字段不能被繼承,但方法會。所以當我有getA()在子類中不會選擇孩子的實例變量? – 2015-04-01 06:23:55