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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

good point, creation vs initialization. I used to get confused with this before.
@dasblinkenlight Thanks for clearing that up and the link was useful.
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.