Hey Guys, I am creating this blog to share deep knowledge in Java, JSP, Servlets, JDBC, Hibernate, Spring and Spring MVC in details.

Is it possible to override a method by changing the return type or what is covariant method overriding in Java?


Is it possible to override a method by changing the return type or what is covariant method overriding in Java?

Before JDK 5.0, it was not possible to override a method by changing the return type. When we override a parent class method, the name, argument types and return type of the overriding method in child class has to be exactly the same as that of the parent class method. The overriding method was said to be invariant with respect to return type.
Java 5.0 onwards it is possible to have different the return type for an overriding method in the child class, but the child’s return type should be sub-type of parent’s return type. The overriding method becomes variant with respect to return type.
Below is a simple example to understand the co-variant return type with method overriding.

class A {
}

class B extends A {
}
class Base {
     A fun() {
          System.out.println("Base fun()");
          return new A();
     }
}
class Derived extends Base {
     B fun() {
          System.out.println("Derived fun()");
          return new B();
     }
}
public class Main {
     public static void main(String args[]) {
          Base base = new Base();
          base.fun();

          Derived derived = new Derived();
          derived.fun();
     }
}
Output:
Base fun()
Derived fun()

Note: If we swap return types of Base and Derived, then above program would not work.
Advantages:
·        It helps to avoid confusing type casts present in the class hierarchy and thus making the code readable, usable and maintainable.
·        We get liberty to have more specific return types when overriding methods.
·        Help in preventing run-time ClassCastExceptions on returns

Share:

Related Posts:

No comments:

Post a Comment

Popular Posts