2015-04-14 36 views
2

下面的對象變量是代碼片段,其輸出 -類成員VS子

class Box{ 
     int height = 1; 
     int length = 1; 
     int width = 1; 

     Box(int h, int l, int w){ 
       this.height = h; 
       this.length = l; 
       this.width = w; 
     } 

     int volume(){ 
       return this.height * this.length * this.width; 
     } 

} 

class BoxWeight extends Box{ 
     int height = 99; 
     int length = 99; 
     int width = 99; 
     int mass; 

     BoxWeight(int h, int l, int w, int m) { 
       super(h, l, w); 
       this.mass = m; 
     } 

     int volume(){ 
       return this.height * this.length * this.width; 
     } 
} 
public class BoxDemo { 
     public static void main(String[] args) { 
       Box b = new Box(10, 20, 30); 
       BoxWeight bw = new BoxWeight(40, 50, 60, 10); 
       System.out.println(bw.height); 
       System.out.println(bw.length); 
       System.out.println(bw.width); 
       //b = bw; 
       //System.out.println(b.volume()); 

     } 

} 

輸出

99 
99 
99 

這裏我不能明白爲什麼目標體重是打印值作爲類初始化成員。爲什麼對象bw沒有保存通過構造函數賦值的值?

+0

其實最終目的是不打印40,50,60,我只是想知道這裏發生的事情發生了什麼。如果任何人都可以在這裏提出一些關於這方面的好消息,這可能會有幫助哪些java機制在這裏工作? –

+0

當在BoxWeight構造函數「」BoxWeight(40,50,60,10)**被調用,它再次調用**超**初始化高度,寬度,長度我認爲所有使用超級初始化將在**這個* *表示BoxWeight對象,其對應的值爲40,50,60。 –

回答

4

BoxWeight的成員隱藏Box的成員,所以您看不到傳遞給Box構造函數的值。

剛剛從BoxWeight刪除該成員:

 int height = 99; 
     int length = 99; 
     int width = 99; 

它也沒有意義,有兩類完全相同的實施volume()

0

這就是繼承是如何工作的。最後的@Override重要。在這種情況下,它是BoxWeight

1

因爲BoxWeight定義它自己的lengthwidthheight,在Box相應的字段是隱藏的。您可以從BoxWeight,或投刪除領域的Box如下:

public static void main(String[] args) { 
    Box b = new Box(10, 20, 30); 
    BoxWeight bw = new BoxWeight(40, 50, 60, 10); 
    System.out.println(((Box) bw).height); 
    System.out.println(((Box) bw).length); 
    System.out.println(((Box) bw).width); 
} 

打印:

40 
50 
60