February 27, 2015

What gets Printed when a.foo() & b.foo() Called ?

Given:

11. class Alpha {
12. public void foo() { System.out.print("Afoo "); }
13. }
14. public class Beta extends Alpha {
15. public void foo() { System.out.print("Bfoo "); }
16. public static void main(String[] args) {
17. Alpha a = new Beta();
18. Beta b = (Beta)a;
19. a.foo();
20. b.foo();
21. }
22. }


A. Afoo Afoo
B. Afoo Bfoo
C. Bfoo Afoo
D. Bfoo Bfoo
E. Compilation fails.
F. An exception is thrown at runtime.







Answer: D


Explanation :

Super class Alpha reference variable to pointing to subclass object beta .So due to Runtime Polymorphism or Dynamic method Dispatch the overridden method foo() of Beta Class Object is called and Not foo method Alpha Class Object.

Even reference variable 'a' is of Type Alpha ,the Overridden method foo of Beta Class is called and therefore Bfoo is Printed first.

Now the reference variable 'a' which is of type Alpha is downcasted to Beta type.Therefore Beta b variable is pointing to Beta Object ,Where Alpha a was pointing to and therefore Beta Object foo method is called which prints Bfoo Again.Option D

Output :Bfoo Bfoo With Warning :Possible Loss of Data By Downcasting.

Remember :Which method is called is decided at runtime by Type of Object and not on Reference variable.Also Compiler only checks whether a reference variable of a Class is having its method or not.

Related Topics

0 comments:

Post a Comment