Saturday 8 June 2019

Core Java | Can overridden methods differ in return type in Java?


Before Java 5.0, Overriding method must match both parameters and return type exactly. In Java 5.0, it introduces a new facility called covariant return type.

In OOPS, 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. We can override a method with the same signature but returns a subclass of the object returned.

class ParentClass {
     Object methodOver() {
           return new Object();
     }
}

class Child extends ParentClass {
     @Override
     String methodOver() {
           return "5";
     }
}

Case 1: If the return type is a primitive data type or void.

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

Example: if return type is int, float, string then it should be the same.

Case 2: If the return type is a derived data type.

Due to covariance return type in JDK 5.0+ versions.


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!!


Related Posts Plugin for WordPress, Blogger...