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:
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.
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()); } }
method does not override or implement a method from a supertype
Learn All in Tamil © Designed & Developed By Tutor Joes | Privacy Policy | Terms & Conditions