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:
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()); } }
ChildClass
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions