简体   繁体   中英

Runtime polymorphism while creating base class object

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?

[...] 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM