2016-07-24 233 views
-1

我對代碼的輸出感到困惑。我想知道變量i和s的每次調用哪個類用於調用變量。這個問題涉及可變陰影。另外我想知道在主要方法中如何保持不斷變化。有人可以向我解釋這段代碼的輸出嗎?

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 –

相關問題