This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Overriding Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Overriding" Watch "Overriding" New topic
Author

Overriding

Pinki Roy
Greenhorn

Joined: May 16, 2008
Posts: 22


Answer is class B - return D

The explanation given in the mock answers is

Explanations : From J2SE 5.0 onwards. You are now allowed to override the return type of a method with a subtype of the original type.

My problem is that but class D does not come in the hierarchy so why do we get this answer?

Vadim Vararu
Ranch Hand

Joined: Jan 03, 2009
Posts: 147
So, till the JAVA SE5 the rule was: when you override a method, the overriding method has to return exactly the same type as the overridden one!
Beginning with JAVA SE5 the rule is: when you override a method, the overriding method has to return any type that is in relation IS-A with the type returned by the overridden method.

So, till JAVA SE5 i could not do this:


Beginning with JAVA SE5 this is legal, because Number and Integer are covariant return types.

So, in your code the class D extends the class C, so if the overridden method returns C, it's quite legal that the overriding method returns D.

Have a good day, Vadim.


If you think you've done too much, usually it means you've done too few.
Pinki Roy
Greenhorn

Joined: May 16, 2008
Posts: 22
Vadim Vararu wrote:So, till the JAVA SE5 the rule was: when you override a method, the overriding method has to return exactly the same type as the overridden one!
Beginning with JAVA SE5 the rule is: when you override a method, the overriding method has to return any type that is in relation IS-A with the type returned by the overridden method.

So, till JAVA SE5 i could not do this:


Beginning with JAVA SE5 this is legal, because Number and Integer are covariant return types.

So, in your code the class D extends the class C, so if the overridden method returns C, it's quite legal that the overriding method returns D.

Have a good day, Vadim.



Thanks you so much Vadim, for clearing my concept.
 
Consider Paul's rocket mass heater.
 
subject: Overriding
 
Similar Threads
Covariant problem
instance access
Explanation for the statements
Polymorphism
Can we have more than one public class in a same program