今天遇到了一個很有意思的問題,父類和子類都定義了一個同名變量,聲明一個父類類型a指向子類實例時,a.變量 = 父類的值
代碼
public class Father {
public int i = 1;
public int f = 2;
public int getI() {
return i;
}
public Father() {
System.out.println("father construct..");
}
}
public class Son extends Father {
public int i = 111;
public int s = 222;
public Son() {
System.out.println("son construct..");
}
@Override
public int getI() {
return i;
}
public static void main(String[] args) {
Father father = new Son();
System.out.println(father.i);
System.out.println(father.getI());
}
}
當子類重寫getI()方法時,控制檯輸出
控制檯輸出:
當子類不重寫getI()方法時,控制檯輸出:
可以看到 ,調用了父類的方法,返回了父類的i值
冷靜分析
打個斷點看看