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 {
     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.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...