问题
I've put this code in the compiler
package com.employer.constractor;
public class ConstractorDemo extends A{
public ConstractorDemo(){
System.out.print("Demo");
}
public static void main(String[] args){
new ConstractorDemo();
}
}
class A {
A(){
System.out.print("A");
}
}
And it gave "ADemo" why? I'll appreciate any detailed answer for this case and mention how compiler will deal exactly with that
回答1:
The child constructor is invoked first. The first line in the child constructor will be a call to super. WHich gives you the illusion that the parent will be invoked first. But in reality the child class's constructor calls the parent class's constructor
回答2:
The constructor of a base class (class A in your case) is always executed before the constructor of the class you are instantiating (class ConstractorDemo in your case). That's why A is printed before Demo.
This constructor :
public ConstractorDemo(){
System.out.print("Demo");
}
is equivalent to :
public ConstractorDemo(){
super (); // prints A
System.out.print("Demo"); // prints Demo
}
回答3:
When you invoke a child constructor, it automatically chain the calls to it's all super classes until the chain reaches to Object class.
Though you are not invoking Invoking a super class constructor doesn't mean that you are executing only Child class constructor alone. There is a interesting fact that your super class constructors(till n'th super class, which is Object class constructor) also calls in that process(shown in your code). you can observe when you invoke any Child constructor. There is a chain call to the immediate parent class constructor from the current class. And the call continues until the Object class constructor invokes since that the possible most Parent classes super class is.
Thumb rules
- If you call any specific super constructor (super or super(args)), then that specific super constructor invokes.
- If you are not calling any specific constructor, then default super constructor(super()) invokes.
回答4:
base class constructor is always executed before the class Level Constructor . it automatic call super class . So First Awill print then after that Demo as per Your example. Thanks
回答5:
Whenever a subclass's constructor is called , the first default statement in it is super(); which is automatically added by the compiler,
The super(); will invoke the constructor of superclass and so, first it will execute A() and then ConstractorDemo()
Refer to this : https://www.javatpoint.com/super-keyword
Even if you want to specify super(); it needs to be the first statement of your constructor else it will give you compile time error!
Your Constructor is like this :
public ConstractorDemo()
{
super(); // u didn't specified this but compiler will automatically add it
System.out.print("Demo");
}
来源:https://stackoverflow.com/questions/34491335/which-executed-first-the-parent-or-the-child-constructor