Overriding a method with different return type in Java

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,

class Base
{
	public Object display(String obj)
	{
		System.out.println("Base.display() " + obj);
		return "0";
	}
}

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

class Derived extends Base
{
	@Override
	public String display(String obj)
	{
		System.out.println("Derived.display() " + obj);
		return "Derived";
	}
}

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,

package com.thispointer.inheritance.example1;

class Base
{
	public Object display(String obj)
	{
		System.out.println("Base.display() " + obj);
		return "0";
	}
}

class Derived extends Base
{
	@Override
	public String display(String obj)
	{
		System.out.println("Derived.display() " + obj);
		return "Derived";
	}
}


public class Example {
	public static void main(String[] args) {
		
		Base baseRef = new Derived();
		
		// Due to dynamic binding, will call the derived class
		// display() function
		String data = (String)baseRef.display("test");
		
		System.out.println(data);

	}

}

Output:

Derived.display() test
Derived

 

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top