9

Please consider the following code.

class Base{
  Base() {  
      print();   
  }
  void print() { 
      System.out.println("Base"); 
  }
}

class Child extends Base{
   int i =   4;
   public static void main(String[] args){
      Base base = new Child();
      base.print();
   }
   void print() { 
       System.out.println(i); 
   }
}

The program will print 0,4.

What I understand by this is, the method to be executed will be selected depending on the class of the actual object so in this case is Child. So when Base's constructor is called print method of Child is called so this will print 0,4.

Please tell if I understood this correctly? If yes, I have one more question, while Base class constructor is running how come JVM can call Child's method since Child's object is not created?

Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
Sumanth Shastry
  • 1,139
  • 1
  • 19
  • 28

2 Answers2

7

[...] the method to be executed will be selected depending on the class of the actual object

Yes, your understanding is correct: the method is selected based on the type of the object being created, so the call is sent to Child.print() rather than Base.print().

while Base class constructor is running how come JVM can call Child's method since Child's object is not created?

When Base's constructor is running, Child object is already created. However, it is not fully initialized. That is precisely the reason to avoid making calls to methods that can have overrides from inside a constructor: the language allows it, but programmers should take extreme care when doing it.

See this Q&A for more information on problems that may happen when base class constructors call overridable methods.

Community
  • 1
  • 1
Sergey Kalinichenko
  • 714,442
  • 84
  • 1,110
  • 1,523
1

the method to be executed will be selected depending on the class of the actual object

yes that is correct.

Base base = new Child();

. It doesn't happen the way you think while Base class constructor is running how come JVM can call Child's method since Child's object is not created? it happens. Here what happens is, Child instance is created, and while Child instance is being created through default constructor of Child, it first calls the super constructor that is where the 0 get printed

Isuru Gunawardana
  • 2,847
  • 6
  • 28
  • 60