简体   繁体   中英

Java class constructors and super() and control flow

I have a basic question about how the control flows between a base class and child class constructors. Look at this snippet.

public class Base{

     public Base(Object obj){
         System.out.println("Super constructor");
     }
}

public class Child{
    super(new Object obj(){
        @Override
        public void create(){
            System.out.println("Inside Super call in child constructor");
        }
    });
    System.out.println("Inside child constructor");
}

What is the order in which the messages are print? I am getting

Super constructor
Inside Super call in child constructor
Inside child constructor

Why is the super contructor getting called before the inline object creation in super call?

First of All, There are many mistakes in your code.
Presuming that you are asking about how the super calls will be executed, I am posting an answer to this question.

Solution:

public class Base {
    public Base(Object obj){
        System.out.println("Super constructor");
    }
}

class Child extends Base {
    public Child(Object obj) {
        super(obj); 
        System.out.println("Inside Child Constructor");
    }
    public static void main(String[] args) {
        Child myChild = new Child("Object");
    }
}

will OUTPUT to:

Super constructor
Inside Child Constructor

Explanation:

When a class hierarchy is created, in what order are the constructors for the classes that make up the hierarchy executed? For example, given a subclass called B and a superclass called A, is A's constructor executed before B's, or vice versa? The answer is that in a class hierarchy, constructors complete their execution in order of derivation, from superclass to subclass. Further, since super( ) must be the first statement executed in a subclass' constructor, this order is the same whether or not super( ) is used. If super( ) is not used, then the default or parameterless constructor of each superclass will be executed.

In your Case:
As soon as your Child object myChild is created using the new keyword, Its constructor is called. In your child class constructor you are providing a call to super(obj) explicitly which calls the constructor of the base class. This results in printing the statement of Base class first, and then printing the content of Child Class.

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