Search code examples
javaoopinheritancepolymorphism

Non-overridden subclass method with same name calling


class Animal{
    void eat(Animal animal){
        System.out.println("animal eats animal");
    }
}

public class Dog extends Animal{
    void eat(Dog dog){
        System.out.println("dog eats dog");
    }

    public static void main(String[] args) {
        Animal a = new Dog();
        Dog b = new Dog();
        a.eat(b);
        b.eat(b);
    }
}

In the above code, the output will be

animal eats animal
dog eats dog

Why this happened?


Solution

  • Probably you expect to see twice "dog eats dog". This does not happen because the two methods have a different signature. Therefore, Dog#eat(Dog) does not override Animal#eat(Animal) but provides a more specific eat method instead.

    If you add @Override to void eat(Dog dog) there will be an error. Using this annotation is good practice because it denotes that the annotated method should override a method declaration in a supertype. If the method does not do that (as in your example) you get the following error to make you aware if it:

    Method does not override method from its superclass


    If you want to override the eat method in Dog, you need to provide the same signature:

    @Override
    void eat(Animal animal) { // instead of eat(Dog dog)
        System.out.println("dog eats dog");
    }