10. public class Foo {
11. public int a;
. public Foo() { a = 3; }
13. public void addFive() { a += 5; }
14. }
and:
20. public class Bar extends Foo {
21. public int a;
22. public Bar() { a = 8; }
23. public void addFive() { this.a +=5; }
24. }
invoked with:
30. Foo foo = new Bar();
31. foo.addFive();
32. System.out.println(”Value: “+ foo.a);
What is the result?
A. Value: 3
B. Value: 8
C. Value: 13
D. Compilation fails.
E. The code runs with no output.
F. An exception is thrown at runtime.
我的分析:
我感觉把实例化Bar传给Foo的过程中,foo是无法接受子类传给它的a值,因为继承本身就覆盖了父类的属性a。所以在Foo foo = new Bar();之后实际只是等于只运行了foo的构造函数。当然,子类的值传不过去,结果就很明显了。
是先执行被继承的类,在执行继承其他类的类。构造里加打印语句就清晰
运行结果证明:答案是A