Co-variant Return Type - Part 1
I'm sharing my experience with you as these are the questions
which have been asked to me while interviewing on java profile.
What is Covariant return type in java?
It means when one overrides a method, the return type of the
overriding method is allowed to be same return type of overridden method or
subtype of the overridden method's return type. From the release of JDK
1.5, covariant types were introduced in java.
Here is a simple example:
public
class
Human
{
protected
Language
speak() {
return
new
Language
();
}
}
Dog
classpublic
class
Man
extends
Human
{
protected
Language
speak() {
return
new
Hindi
();
}
}
It's possible to modify the return type of the Man's speak()
method to Hindi- a sub class of Language, as shown below:
protected
Hindi
speak() {
return
new
Hindi
();
}
That's perfectly a legal overriding, and the return type of Man's
speak() method is know as Covariant return type.
If you still have any
question you can reach me any time through email (jigyasu2010@hotmail.com)
Comments
Post a Comment