Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism and static methods

 
Ida Achi
Greenhorn
Posts: 26
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
From K&B SCJP6 masterexam:

Could somebody please be kind and explain why the answer is B . Thanks.

Given:



Answers:

A. ab
B. ad
C. cb
D. cd
E: Compilation fails


 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
there is no polymorphism on static methods that is they will be called depending upon the reference used while instance methods are called depending upon the real object at runtime.
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
No, the answer should be E.

There's a syntax error in line 12, for example. And if you fix the obvious typo, then there's a syntax error in line 15.
 
Neha Daga
Ranch Hand
Posts: 504
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
i guess different method names for static methods is also a typo.
 
Paul Clapham
Sheriff
Posts: 21416
33
Eclipse IDE Firefox Browser MySQL Database
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Neha Daga wrote:i guess different method names for static methods is also a typo.


Yes, you're probably right. But asking a question about some code, and then posting different code, is really a waste of people's time. And in the certification exams, details are very important.
 
Abhishek Sawant
Greenhorn
Posts: 13
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I agree with Paul. Everyone should write or ask question without any typing mistake. It can create confusion among new users. As far as question is concerned, person who has posted this question should edit it & write it correctly to avoid further confusion.
If answer B is believed to be correct, then line 15 should be read as c.my();
Since my() is a static method, it cannot be overridden. static methods are shared by all instances of class. on line 15, any of the following code will give same output that is a.
c.my();
my();
Car.my();
Mini.my();
Line 16 gives output as d.
Even though we have reference of Car, at run time Java Virtual Machine checks whether the instance to which reference is referring to has the method with same name or not.(Comment line 12, & run the code, output will be ab). If it has, then method m2 gets overridden.(which is why you get output as d).
So, the final output is ad.

I hope the answer has cleared your doubts.
All the best.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic