Subclass Method Changes Return Type to a Different Class in Interface In Java


Write a Java program to demonstrate method overriding with a subclass that overrides a method from an interface and changes the return type to a different class

The interface MyInterface with a method myMethod that returns an instance of ParentClass. You also have two classes, ParentClass and ChildClass, where ChildClass is a subclass of ParentClass. Finally, you have a class MyClass that implements MyInterface, providing an implementation of the myMethod method to return an instance of ChildClass. Here's a breakdown of what your code does:

  • MyInterface is an interface with a method myMethod that returns an instance of ParentClass.
  • ParentClass is a class with a method getClassName that returns the string "ParentClass."
  • ChildClass is a subclass of ParentClass. It overrides the getClassName method to return the string "ChildClass."
  • MyClass is a class that implements MyInterface. It provides an implementation of the myMethod method that returns an instance of ChildClass.
  • In the Main class's main method, you create an instance of MyClass named myInterface.
  • You call the myMethod method on the myInterface object, which returns an instance of ChildClass.
  • You assign the result to a ParentClass reference variable, result.
  • Finally, you call the getClassName method on the result object and print the result to the console.

Source Code

interface MyInterface
{
    ParentClass myMethod();
}
 
class ParentClass
{
    String getClassName()
	{
        return "ParentClass";
    }
}
 
class ChildClass extends ParentClass
{
    String getClassName()
	{
        return "ChildClass";
    }
}
 
class MyClass implements MyInterface
{
    @Override
    public ChildClass myMethod()
	{
        return new ChildClass();
    }
}
 
public class Main
{
    public static void main(String[] args)
	{
        MyInterface myInterface = new MyClass();
        ParentClass result = myInterface.myMethod();
        System.out.println(result.getClassName());
    }
}

Output

ChildClass