Saturday, 8 June 2019

Core Java | 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 the same.

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

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

class TestCovariant 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...