代碼執行順序的題目
public class TestClass {
static class Father{
public int money = 1;
public Father() {
this.money = 2;
showMoney();
}
protected void showMoney(){
System.out.println("I am Father , I hava $"+money);
}
}
static class Son extends Father{
public int money = 3;
public Son() {
this.money = 4;
showMoney();
}
protected void showMoney(){
System.out.println("I am Son , I hava $"+money);
}
}
public static void main(String[] args) {
Father guy = new Son();
System.out.println("This guy has $"+guy.money);
}
}
結果:
流程:
-
執行main的第一句
Father guy = new Son();
- 先執行父類的
- 屬性賦值
public int money = 1;
- 父類的構造器
public Father() { this.money = 2; showMoney(); //這裏調的是Son的showMoney() }
- Son的showMoney()
這時候son的money是0,因此第一條輸出是I am Son , I hava $0
protected void showMoney(){ System.out.println("I am Son , I hava $"+money); }
- 屬性賦值
- 執行Son的屬性賦值
public int money = 3;
- 執行Son的構造器
此時在構造器裏把money賦值成了4,所以調用 showMoney()的輸出爲public Son() { this.money = 4; showMoney(); }
I am Son , I hava $4
- 先執行父類的
-
執行main的第二句
System.out.println("This guy has $"+guy.money);
由於new 出來的對象是Father類型的,所以guy.money應該調的是father.money,由於之前在father的構造器裏把father.money賦值成了2,所以這步輸出爲
This guy has $2