What happens if a superclass method is overridden by more than one subclass in Java?

When multiple subclasses override the same method from a superclass, each subclass provides its own implementation of that method. At runtime, Java executes the overridden method based on the actual object type, not the reference type. This behavior is known as runtime polymorphism or dynamic method dispatch.

Key Points: • Each subclass can provide a different implementation of the same inherited method. • The overridden method that gets executed depends on the actual object created at runtime. • This is a key feature of runtime polymorphism. • A superclass reference can point to objects of different subclasses. • Java automatically calls the appropriate overridden method based on the object's type.

Example: Consider an Animal superclass with a makeSound() method. Different subclasses such as Dog and Cat can override this method to provide their own behavior.

Code Example:

class Animal {

    void makeSound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {

    @Override
    void makeSound() {
        System.out.println("Dog barks");
    }
}

class Cat extends Animal {

    @Override
    void makeSound() {
        System.out.println("Cat meows");
    }
}

public class Demo {

    public static void main(String[] args) {

        Animal animal1 = new Dog();
        Animal animal2 = new Cat();

        animal1.makeSound();
        animal2.makeSound();
    }
}

Output:

Dog barks Cat meows

How It Works:

• Dog overrides makeSound() with its own implementation. • Cat also overrides makeSound() with a different implementation. • When makeSound() is called, Java checks the actual object type. • The corresponding subclass method is executed.

Real-World Example:

A Payment superclass or interface may define:

processPayment()

Different implementations:

• CreditCardPayment → Processes card payments • UpiPayment → Processes UPI payments • NetBankingPayment → Processes bank transfers

Each class overrides the same method but performs different actions.

Benefits:

• Supports flexible and extensible designs • Enables runtime polymorphism • Promotes code reuse through inheritance • Makes applications easier to maintain and extend

Interview Tip: A concise interview answer is:

"If multiple subclasses override the same superclass method, each subclass maintains its own implementation. When the method is called through a superclass reference, Java executes the version belonging to the actual object type at runtime, which is an example of runtime polymorphism."