Thursday, 28 July 2016

Covariant return type

In object-oriented programming, a covariant return type of a method is one that can be replaced by a "narrower" type when the method is overridden in a subclass.

C# does not support return type covariance. Covariant return types have been (partially) allowed in the Java language since the release of JDK5.0.

However if the return type is void or primitive then the data type of parent class method and overriding method should be same.

class Parent { 
     Parent getCovariant() {
           return this;
     }

     voidgetMessage() {
           System.out.println("Covariant return type!!");
     }
}

classTestCovariant extends Parent {

     TestCovariant getCovariant() {
           return this;
     }

     public static void main(String args[]) { 
           new TestCovariant().getCovariant().getMessage(); 
     } 
}
Output:
Covariant return type!!

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...