March 05, 2015

What is the result When f.addFive() and System.out.println(f.a) is Called ?

Given:

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

Explanation :

At run-time JVM calls the overridden method (addFive) of the Class Bar which extends Foo.Since this.a + = 5 is written in Line 37,Bar Object's integer variable a = 8 is added with 5 and will have its result 13.Then b is printed .


after executing or printing b,we have now a tricky part where f.a is written withing System.out.prinln () method.Question arises - Which value of a is printed ? Is it a value of Bar Class or a value of Foo class.

Always at Run-time JVM calls only overridden method of subclass which is decided by the Type of Object(In the above case Bar is the type of Object).But whenever we call or invoke any other data member like class's variables,It is decided by Type of Reference variable  and not by type of Object.

In the above question f.a , f is of type Foo ,now compiler first checks whether class Foo has int a variable ? -- Yes ,if it has ,Then call that Foo class int a value .Therefore a value 3 is printed along with b. (b 3) - Option A.

Related Topics

0 comments:

Post a Comment