2016-07-24 12 views
-1

私はコードの出力に混乱しています。私は変数iとsの各呼び出しについて知りたい。変数は変数を呼び出すために使われる。疑問は、可変シャドウイングです。また、mainメソッドの中でどのように線が変化していくのか知りたい。ここで誰かが私にこのコードの出力を説明できますか?

public class A { 
    public int i = 0; 
    public static String s = ""; 

    public A(int i) { 
     System.out.println(i); 
     s += "x"; 
    } 

    public A debug() { 
     if (this instanceof B) { 
      System.out.println("Spam"); 
      s += "s"; 
     } 
     return this; 
    } 
} 
public class B extends A { 
    public int i = 100; 
    public static String s = "s"; 

    public B(int i, String s) { 
     super(i); 
     this.i += 5; 
     this.s = s; 
    } 

    public static void main(String[] argv) { 
     String s = ""; 
     B b = new B(0, s); 
     System.out.println(b.i + " " + b.s); 
     s += "foo"; 
     A a = new B(42, s); 
     System.out.println(a.i + " " + a.s); 
     System.out.println(b.debug().s + " " + b.i + " " + b.s); 
     System.out.println(a.debug().s + " " + a.i + " " + a.s); 
    } 
} 

は、そのコードの出力です:

0 
105 
42 
0 xx 
Spam 
xxs 105 foo 
Spam 
xxss 0 xxss 
+3

は、それがそのウェブサイトから削除されますどのような場合には...ここにコードを挿入しますか?その質問は役に立たないでしょう。 –

+1

あなたが何を求めているのか分かりません。あなたは "質問番号3の出力を得る方法"を尋ねました。その出力を生成するコードは、そのすぐ上に表示されます。その出力を得るには、そのコードを実行します。私は何を誤解していますか? – smarx

+0

質問は少し厄介な言葉ですが、明らかに「なぜコードがその出力を生成するのですか」と尋ねています。 – JJJ

答えて

0
public class A { 
    public int i = 0; //not changed, because it is not overrided 
    public static String s = ""; 

    public A(int i) { 
     System.out.println(i); //1. 0, 3. 42 
     s += "x"; //After second run s="xx", because it is static 
    } 

    public A debug() { 
     if (this instanceof B) { 
      System.out.println("Spam"); //5, 7. Spam 
      s += "s"; //s = "xxs", than "xxss" because it is static 
     } 
     return this; 
    } 
} 
public class B extends A { 
    public int i = 100; 
    public static String s = "s"; 

    public B(int i, String s) { 
     super(i); 
     this.i += 5; //First run: i=105, Second run: i=47 
     this.s = s; //First run: public static String s="", Second run: public static String a.s="foo" 
    } 

    public static void main(String[] argv) { 
     String s = ""; 
     B b = new B(0, s); 
     System.out.println(b.i + " " + b.s); //2. 105 
     s += "foo"; //B.s is now foo 
     A a = new B(42, s); 
     System.out.println(a.i + " " + a.s); //3. 0 xx 
     System.out.println(b.debug().s + " " + b.i + " " + b.s); //1. because of (A)b.s = xxs, 2. b.i = 105, 3. b.s = foo 
     System.out.println(a.debug().s + " " + a.i + " " + a.s); //(A)a.s = "xxss", (A)a.i = 0, (A)a.s = "xxss" 
    } 
} 
+0

わかりますか? –

+0

この質問に関係するトピックについてどこで知ることができますか?シャドーイングとオーバーライドのトピックを説明するソースを見つけることができないようです。 – user2966968

+0

https://docs.oracle.com/javase/tutorial/java/TOC.html –

関連する問題