Covariant return types the overriding method's return type is subtype of the overriden method's return type
santhosh Gopalakrishna Bajja
Ranch Hand
Joined: Apr 01, 2006
Posts: 34
posted
0
class A{ int x=5; }
class B extends A { int x=6; }
public class CovariantTest { public A getObject() { return new A(); }
public static void main(String[] args) { CovariantTest c1 = new SubCovariantTest(); System.out.println(c1.getObject().x); } }
class SubCovariantTest extends CovariantTest { public B getObject() { return new B(); } }
It returns 5 why not 6.
Does this mean Covarient return types are similar to static methods.
Two methods with different return types one in superclass and one in subclass. method return type should be subtype of superclass method return type is what i understood.
Confussing Boss Please Explain me what is happening.
the Covarient return type will allow to override the Super class method with the derived class method,where the Return type must be sub class of the Super class method Return Type.
Regards<br /> <br />Mohammed Yousuff M N <br /> <br />Try NOT to Become a man of SUCCESS, BUT Try to Become a man of VALUE..
this is my first reply , so if i make any mistakes please correct me.
ex:
public class Super {
}
public class Sub extends Super {
}
public class TestCovariant { Sub s = Sub(); public Super checkReturnType() {
return s; } }
The key is that the method checkReturnType() is of type Super. But Sub reference s is returned, Since Sub is a sub class of Super we can return the Sub object. This is true as os jdk 1.5 but when we use as jdk 1.4 then it gives an error.