简体   繁体   English

用构造函数创建新对象

[英]Creating new object with constructor

The following code, when compiled and run gives the output as "alpha subsub". 以下代码在编译和运行时给出的输出为“ alpha subsub”。 SubSubAlpha(); constructor should add "subsub " to variable s and that should be the output. 构造函数应将“ subsub”添加到变量s ,这应该是输出。

How come the output is " alpha subsub"? 输出为何是“ alpha subsub”?

class Alpha {
    static String s = " ";

    protected Alpha() {
       s += "alpha "; 
    }
}

public class SubSubAlpha extends Alpha {
    private SubSubAlpha() { 
       s += "subsub "; 
    }

    public static void main(String[] args) {
        new SubSubAlpha();
        System.out.println(s);
        // This prints as " alpha subsub".
        //Shouldn't this one be printed as " subsub"
        //Who made the call to Alpha(); ?
    }
}

This is because when you create the object, the constructor of parent is invoked and it goes upto the Object class. 这是因为在创建对象时,将调用parent的构造函数,并将其转到Object类。 Your Alpha internally extends Object class. 您的Alpha内部扩展了Object类。 So first SubSubAlpha constructor is invoked which calls Alpha constructor which in turn calls Object constructor, and the execution flows from Object through Alpha and in the end SubSubAlpha 因此,首先调用SubSubAlpha构造函数,该构造函数调用Alpha构造函数,而Alpha构造函数又调用Object构造函数,执行过程从Object到Alpha,最后是SubSubAlpha

For Information 有关信息
Constructor calling hierarchy is that constructor of parent is called and then constructor of child gets called. 构造函数调用层次结构是先调用parent的构造函数,然后再调用child的构造函数。 But if you call a method, it is searched in the child class. 但是,如果您调用方法,则会在子类中对其进行搜索。 If not found in the child class, then that method is searched in the parent class. 如果在子类中未找到,则在父类中搜索该方法。

Reference 参考
Order of Constructor Call 构造函数调用的顺序

When calling the contructor of a subclass the first instruction is a call to the super class contructor. 当调用子类的构造函数时,第一条指令是对超类构造函数的调用。

So when you create a SubSubAlpha object, the Alpha constructor adds alpha to s property and then SubSubAlpha constructro adds subsub 因此,当您创建SubSubAlpha对象时, Alpha构造函数将alpha添加到s属性,然后SubSubAlpha构造将添加subsub

Let me just slightly rewrite your contructor, with no change in the resulting bytecode : 让我稍微重写一下您的构造函数, 结果字节码没有变化

private SubSubAlpha() { super(); s += "subsub "; }

Now it should be immediately clear what gets executed and in what order. 现在应该立即清除执行的内容和执行顺序。

When there is an hierarchy of classes the constructor of the subclass, in this case SubSubAlpha , always calls (first) the constructor of the superclass, in this case Alpha . 如果存在类的层次结构,则子类的构造函数(在这种情况下为SubSubAlpha )始终(首先)调用超类的构造函数(在本例中为Alpha

So what happens is actually: 所以实际上是:

private SubSubAlpha() { 
    super();
    s += "subsub ";
}

Thus, this makes: 因此,这使得:

s += "alpha ";
s += "subsub ";

Making the string "alpha subsub " 使字符串“ alpha subsub”

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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