2012-09-03 115 views
6

在一個類中,與超類中的字段具有相同名稱的字段隱藏了超類的字段。Java中的隱藏字段繼承

public class Test { 

    public static void main(String[] args) { 

     Father father = new Son(); 
     System.out.println(father.i); //why 1? 
     System.out.println(father.getI()); //2 
     System.out.println(father.j); //why 10? 
     System.out.println(father.getJ()); //why 10? 

     System.out.println(); 

     Son son = new Son(); 
     System.out.println(son.i); //2 
     System.out.println(son.getI()); //2 
     System.out.println(son.j); //20 
     System.out.println(son.getJ()); //why 10? 
    } 
} 

class Son extends Father { 

    int i = 2; 
    int j = 20; 

    @Override 
    public int getI() { 
     return i; 
    } 
} 

class Father { 

    int i = 1; 
    int j = 10; 

    public int getI() { 
     return i; 
    } 

    public int getJ() { 
     return j; 
    } 
} 

有人可以解釋我的結果嗎?

+1

根據你的理解隱藏和繼承是什麼意思;你爲什麼認爲價值觀是他們的方式?你應該可以爲自己解決這個問題。 –

+0

這是功課嗎? –

+0

兒子不是隱藏變量的父類型 – jsj

回答

8

在java中,字段不是多態的。

Father father = new Son(); 
System.out.println(father.i); //why 1? Ans : reference is of type father, so 1 (fields are not polymorphic) 
System.out.println(father.getI()); //2 : overridden method called 
System.out.println(father.j); //why 10? Ans : reference is of type father, so 2 
System.out.println(father.getJ()); //why 10? there is not overridden getJ() method in Son class, so father.getJ() is called 

System.out.println(); 

// same explaination as above for following 
Son son = new Son(); 
System.out.println(son.i); //2 
System.out.println(son.getI()); //2 
System.out.println(son.j); //20 
System.out.println(son.getJ()); //why 10? 
+0

剛剛在java?任何其他語言在字段上提供多態性? – UnKnown

2

Overriding and Hiding Methods

是被調用隱藏方法的版本取決於它是否是從超類或子類調用。

即當調用該子類中經由一個超類引用被調用超類方法覆蓋的方法和它訪問超類成員。

這就解釋了以下作爲所使用的參考是超類:

System.out.println(father.i); //why 1? 
System.out.println(father.j); //why 10? 
System.out.println(father.getJ()); //why 10? 

類似地,對於以下內容:

System.out.println(son.getJ()); //why 10? 

因爲getJ()Son限定的Father版本被調用它認爲構件在Father類中定義。

如果您看過Hiding Fields;他們特別不推薦這樣的編碼方法:

一般來說,我們不建議隱藏字段,因爲它會使代碼難以閱讀。