1
abstract class Animal {
    
    public void test1() {
        System.out.println(" Animal test1");
        test2();
    }
    
    public void test2() {
        System.out.println(" Animal test2");
    }
}


class Cat extends Animal {

    @Override
    public void test2() {
        System.out.println(" Cat Test2 ");
    }    
}


public class MyClass {
 
 public static void main(String [] args) {
        Animal a = new Cat();
         a.test1();
    }
}

So,

why the first call is to test1 method of Animal class ? and, why test2() method call from test1() method resolves to test2() method of child class ?

I tried to understand from Call method from another method in abstract class with same name in real class, but could not understand much.

  • Where else do you think `a.test1()` should go? – Thilo May 01 '21 at 06:38
  • 1
    Oracle has a Java tutorial that explains this very well in [Polymorphism](https://docs.oracle.com/javase/tutorial/java/IandI/polymorphism.html) – Scratte May 01 '21 at 06:51

1 Answers1

2

This is happening because of the concept of Method Overriding.

The statement

Animal a = new Cat();

assigns an object of type Cat to a reference of type Animal. When the statement

a.test1();

is executed. The runtime environment infers the type of a which is Cat. Since the Cat class doesn't define a test1() method of its own, it calls the one which was inherited from the Animal class.

Similarly, when a call to test2() is encountered, first the Cat class methods are checked. Since, the Cat class has a test2() method, with the exact signature as the test2() method of the Animal class, the Cat class method is called. This concept is known as method overriding.

In short, when we try to call a subclass method, using a superclass reference, it first checks for the method, in the subclass, then its superclass and so on.

Charchit Kapoor
  • 8,934
  • 2
  • 8
  • 24
  • 2
    This concept is also more known as [polymorphism](https://en.wikipedia.org/wiki/Polymorphism_(computer_science)) :) – Scratte May 01 '21 at 06:47