2016-08-15 5 views
-4

なぜsuperには影響しませんiフィールドCのフィールド? 出力は012ですが、クラスがCに拡張されているので、なぜ321でないのですか?フィールド用Javaスーパー

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

からsuper.testMethod()呼び出し方法testMethodを実行して、

あなたは可能性は、単に別のタイトルであなたの質問に数回を投稿することが本当にnesseccaryですか? –

+0

今日同じ質問 –

+0

@アンドレアス:まあ、それは同じ質問ではない、それはフォローアップだ。 – Thilo

答えて

1

superは、オーバーライドされたメソッドにアクセスするために使用できます。あなたのシナリオでは、iはBの継承されたメンバーです。

Cで定義されたBのメソッドをオーバーライドすると、superキーワードを使ってBから呼び出すことができます。クラスBiの独自のバージョンを宣言していないため

+1

は、「使用可能」または「使用中」に「使用されている」と言い換えることを検討してください。 – Bathsheba

2

super.iはちょうどthis.i(または単にi)を意味し、それはすでにCからフィールドを継承します。

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

コンストラクタが最初に行う必要があるのは、スーパーコンストラクタの1つを呼び出すことです。だから、これは同等です:あなたが見ることができるように

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にアクセスするだけです。 parentclass