What is the result?

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?

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.



Leave a Reply 2

Your email address will not be published. Required fields are marked *


Matti

Matti

A is correct. In runtime the addFive method of object Bar is invoked, but in the next assignment, the public attribute a in class Foo is invoked.

Sathya janaki

Sathya janaki

Answer is A.

Explanation
—————
Foo f = new Bar();
f.addFive(); // subclass method will be result
System.out.println(f.a); //superclass instance will be reult
(i.e) is
here sub class object is created with super class refernce.
So when we call that reference object.,
the outut is
if we call method, then subclass method will be result
and if we invoke for variable, superclass instance will be reult