In this article we will discuss how to override a method in Java with different return type.

The basic rule for overriding a method in Java is that the new overriding method in derived class should have same signature as of Base class’s method. But there is on exception to this rule i.e.

Overriding method can have different return type but this new type should be,

  • A Non-Primitive.
  • A Subclass of what base class’s overridden method is returning i.e. co-variant Return Type.

Lets see an example,

Suppose we have a Base class,

Now lets create a Derived class, that extends this Base class and overrides the display() function.

In this Derived class we have overridden the display() function, but it has the different return type.

Base class’s display() function has return type ——- Object

Derived class’s display() function has return type ——- String

Just like every other class in Java, String class extends the Object class i.e. String is a sub-type of Object. Hence we can use it as return type in overridden display() function instead of type Object as in Base class.

Basically Base class’s display() method has a covariant return type.

Complete example is as follows,

Output: