Subclass Method Overrides Superclass Method with Different Return Type In Java


Create a Java program to demonstrate method overriding with a subclass that overrides a method with a different return type

Override a method in a subclass (Subclass) with a different return type than the overridden method in the superclass (Superclass). This is not allowed in Java because method overriding requires that the method signature, including the return type, must be the same or covariant. Here's an explanation of the code:

  • Superclass is a class with a method getNumber() that returns an int with the value 10.
  • Subclass is a subclass of Superclass. In the Subclass, you're trying to override the getNumber method with a different return type of double (20.5). This is not allowed and will result in a compilation error.
  • In the MethodOverridingDemo class's main method, you create instances of both Superclass and Subclass.
  • You call the getNumber method on both superObj and subObj.

As mentioned, trying to override a method with a different return type will result in a compilation error. In your code, the compilation error will occur in the Subclass when you attempt to override the getNumber method with a double return type.

Source Code

class Superclass
{
    public int getNumber()
	{
        return 10;
    }
}
 
class Subclass extends Superclass
{
    // This method tries to override getNumber with a different return type
    // This will result in a compilation error
    public double getNumber()
	{
        return 20.5;
    }
}
 
public class MethodOverridingDemo
{
    public static void main(String[] args)
	{
        Superclass superObj = new Superclass();
        Subclass subObj = new Subclass();
 
        System.out.println("Superclass Number : " + superObj.getNumber());
        System.out.println("Subclass Number : " + subObj.getNumber());
    }
}

Output

method does not override or implement a method from a supertype