java有人能给我解释一下这段代码的输出吗?
我对代码的输出感到困惑。我想知道每次调用变量I和s时,使用哪个类来调用变量。这个问题涉及变量跟踪。我还想知道在main方法中,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
# 1 楼答案