The covariant return type indicates that the return type may vary
in a direction similar to that of the subclass.
Changing the return type was not a supported method overriding
strategy prior to Java 5. However, since Java 5, it is now possible to
override a method by altering the return type. This is true if a
subclass overrides a method whose return type is Non-Primitive but
changes it to a subclass type.
// Java example of Covariant Return Type
class A { } class B extends A { } class C { // Method of this class is A class return type A fun(){ System.out.println("Class A"); return new A(); } } class D extends C{ // Method of this class is B class return type B fun(){ System.out.println("Class B"); return new B(); } } public class Main{ // main method public static void main(String args[]) { C c=new C(); c.fun(); D d=new D(); d.fun(); } }
Output:
Class A
Class B
// Java example of Covariant Return Type
class A{ A fun(){ return this; } void Display() { System.out.println("Inside class A "); } } class B extends A { @Override B fun(){ return this; } void Display(){ System.out.println("Inside class B"); } } class C extends B{ @Override B fun() { return this; } @Override void Display(){ System.out.println("Inside class C"); } } public class Main{ // main method public static void main(String argvs[]){ A a = new A(); a.fun().Display(); B b = new B(); b.fun().Display(); C c = new C(); c.fun().Display(); } }
Output:
Inside class A
Inside class B
Inside class C
Post your comment