2

Consider this:

class Animal {
    Animal(){
        System.out.println("Animal's constructor called");
        this.indentifyMyself();//??????????????
        System.out.println("Exit Animal's constructor");
    }
    void indentifyMyself(){
        System.out.println("I'm an Animal");
    }
}
class Human extends Animal{
    Human(){
        System.out.println("Human's constructor called");
        super.indentifyMyself();
        System.out.println("Exit Human's constructor");
    }
    @Override
    void indentifyMyself(){
        System.out.println("I'm Human");
    }
}
public class Main {

    public static void main(String[] args) {
        new Human();

    }
}

Why does it print?

Animal's constructor called

I'm Human (??? I didn't expect this)

Exit Animal's constructor

Human's constructor called

I'm an Animal

Exit Human's constructor

And not:

Animal's constructor called

I'm an Animal

Exit Animal's constructor

Human's constructor called

I'm an Animal

If anyone can give a detailed explanation of this behavior, I will be very grateful. Please don't tell me redundant answers like "is a Polymorphic java behaviour". Thank in advance

Nicholas K
  • 15,148
  • 7
  • 31
  • 57
Litiec
  • 65
  • 9

2 Answers2

2

The line

I'm Human

is printed instead of the expected

I'm an Animal

because the actual runtime type of the instance is Human and not Animal, hence the overridden function is chosen from the virtual method table.

As discussed here, the behaviour of Java and C++ differs in this aspect.

Codor
  • 17,447
  • 9
  • 29
  • 56
  • Thank, I can understand that and this is all about architecture. Yet is a bit confusing. As I understood when we create a derived class this is what happens: 1st initiates the base class and then the derived class. So when it calls the base class constructor (I thought that), in theory the Human instance does not exist yet, because it wasn't initiated at that point. So that's why I didn't aspect this behaviour. Thank – Litiec Sep 05 '18 at 14:14
0

You have overridden that method and in run-time JVM executes that overridden new version of the method. Not the old one in Animal class

Randula Koralage
  • 328
  • 2
  • 10