31. class Foo {
32. public int a = 3;
33. public void addFive() { a += 5; System.out.print("f "); }
34. }
35. class Bar extends Foo {
36. public int a = 8;
37. public void addFive() { this.a += 5; System.out.print("b " ); }
38. } Invoked with: Foo f = new Bar(); f.addFive(); System.out.println(f.a);
What is the result?
A. b 3
B. b 8
C. b 13
D. f 3
E. f 8
F. f 13
G. Compilation fails.
H. An exception is thrown at runtime.
Answer: A
When we call f.addFive, we call it for the actual type (which is Bar). So from here we got the "b".
Next, we have a "hidding" issue with the variable "a": in Java variable names are resolved using the reference type (which is Foo in this case) and not the object which it is referring, so f.a refers to the "a" from Foo and we got the "3".
No comments:
Post a Comment