Wednesday, 15 June 2016

Can overridden methods differ in return type in Java?

Before Java 5.0, Overriding method must match the 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.

An overriding method in a subclass can return an object whose type is a subclass of the type returned by the method with the same signature in the superclass.

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

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

Case 1: If the return type is 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 same.

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

Case 2: If the return type is derived data type.
Due to covariance return type in JDK 5.0+ versions.

No comments:

Post a Comment

Related Posts Plugin for WordPress, Blogger...