"Covariant return" in Java : Changing return type of a overridden methods...  

Posted by ChEthAn in

Java 1.5 come up with a feature of changing the return type of an overridden method in a subclass this is known as covariant return.

Here I had given an example, how we can override the method of super class with a covariant return in sub class.

/************************************************/
package org.sample;

public class SuperClass {

public SuperClass sampleMethod (int count){
System.out.println("I am in Super class");
return new SuperClass();
}
}
/************************************************/
package org.sample;

public class SubClass extends SuperClass {
public SuperClass sampleMethod (int count) {
System.out.println("I am in Sub class");
return new SuperClass();
}
/**
* @param args
*/
public static void main(String[] args) {
SuperClass sc = new SubClass();
sc.sampleMethod (5);
}
}

/************************************************/
When we run "SubClass" class, we will get output as
I am in Sub class

This shows that we can change the return type of the overriding method only if the new return type is a subtype of the declared return type. And another thing we have to keep in mind is, this Covariant return type is possible only in java 1.5 and in advance version.

This entry was posted on Thursday, January 15, 2009 at Thursday, January 15, 2009 and is filed under . You can follow any responses to this entry through the comments feed .

0 comments

Post a Comment