2016-08-15 31 views
-4

爲什麼superi字段C沒有影響? 輸出爲012,但爲什麼不是321,因爲B類擴展了C類?java super for字段

public class C { 
     protected int i; 

     public C(int i){ 
      this(i,i); 
      System.out.print(this.i); 
      this.i=i; 
     } 

     public C(int i, int j) { 
      System.out.print(this.i); 
      this.i=i+j; 
     } 

     public C(){ 
       this(1); 
       System.out.print(i); 
     } 

     public static void main(String[] args) { 
      C c=new C(); 
     } 
} 

public class B extends C{ 
     public B(){ 
       super.i=3; 
     } 



     public static void main(String[] args){ 
      C c=new B(); 
     } 
} 
+2

難道真的nesseccary做super.testMethod()調用的方法testMethod只是用不同的標題發表您的問題幾次? –

+0

今天同樣的問題 –

+0

@Andreas:恩,這不是同一個問題,而是後續問題。 – Thilo

回答

1

super可用於訪問重寫的方法。在您的場景中,i是B的繼承成員。

如果覆蓋C中定義的B中的方法,則可以使用super關鍵字從B中調用它。

+1

考慮將「正在使用」改爲「可以使用」或「正在使用」。 – Bathsheba

2

super.i只是指this.i(或簡稱i),因爲類B沒有聲明其自身的i版本,因此從C已經繼承了場。

public B(){ 
      super.i=3; // the super here does not do anything 
    } 

構造函數需要做的第一件事是調用其中一個超級構造函數。因此,這是等同於:

public B(){ 
      super(); 
      i=3; 
    } 

正如你所看到的,之前i設置爲3。這就是爲什麼它打印舊值執行超類C的代碼。

0

這很簡單。 That's發生了什麼:

B Constructor is called. 

B doesn´t have an explicit super constructor call- so implicity call super(). 

C() Constructor is called -> call C(int) 

C(int) Constructor is called -> call C(int,int); 

C(int, int) is called. print i. i only has the default value yet so print ->0 

C(int, int) does increment i by j, which at this point is 1+1 = 2 

C(int) Constructor callback, as C(int, int) is done, print i = 2 

C(int) sets i = 1 and prints i = 1. 

B() callback as C() is done. set instance variable i to 3. 

正如你可以看到你有不同的輸出021和that's大家,確實會發生。

我不知道你最初的意圖是什麼,但super可以有不同的含義。

在構造函數中,您通常會使用super訪問父項構造函數。

通過做super.i您只能訪問父類的實例變量i

,你可以通過從父類