为什么输出是:
> B.foo(): bar = null
> B.foo(): bar = B.bar
>a.bar = A.bar
>B.foo(): bar =B.bar
但不是:
> B.foo(): bar = null > A.foo(): bar = A.bar >a.bar = A.bar >B.foo(): bar =B.bar
1)B延伸A所以它不打算给A级打电话吗? 2)为什么a.bar类被调用而不是B? 3)你能解释一下输出吗? 代码:
public class A {
String bar= "A.bar";
A() { foo(); }
public void foo() {
System.out.println("A.foo(): bar = "+ bar);
}
}
public class B extends A {
String bar= "B.bar";
B() { foo(); }
public void foo() {
System.out.println("B.foo(): bar = "+ bar);
}
}
public class C {
public static void main(String[] args) {
A a= newB();
System.out.println("a.bar = "+ a.bar);
a.foo();
}
}