且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么 this() 和 super() 必须是构造函数中的第一条语句?

更新时间:2022-03-13 16:29:08

父类的构造函数需要在子类的构造函数之前调用.这将确保如果您在构造函数中调用父类上的任何方法,则父类已经正确设置.

The parent class' constructor needs to be called before the subclass' constructor. This will ensure that if you call any methods on the parent class in your constructor, the parent class has already been set up correctly.

你试图做的,将 args 传递给超级构造函数是完全合法的,你只需要在你正在做的时候内联构造这些 args,或者将它们传递给你的构造函数,然后将它们传递给 super代码>:

What you are trying to do, pass args to the super constructor is perfectly legal, you just need to construct those args inline as you are doing, or pass them in to your constructor and then pass them to super:

public MySubClassB extends MyClass {
        public MySubClassB(Object[] myArray) {
                super(myArray);
        }
}

如果编译器没有强制执行此操作,您可以这样做:

If the compiler did not enforce this you could do this:

public MySubClassB extends MyClass {
        public MySubClassB(Object[] myArray) {
                someMethodOnSuper(); //ERROR super not yet constructed
                super(myArray);
        }
}

如果父类具有默认构造函数,编译器会自动为您插入对 super 的调用.由于Java 中的每个类都继承自Object,因此必须以某种方式调用对象构造函数,并且必须首先执行它.编译器自动插入 super() 允许这样做.强制 super 首先出现,强制构造函数体以正确的顺序执行,即:对象 ->父级 ->孩子 ->ChildOfChild ->不久之后

In cases where a parent class has a default constructor the call to super is inserted for you automatically by the compiler. Since every class in Java inherits from Object, objects constructor must be called somehow and it must be executed first. The automatic insertion of super() by the compiler allows this. Enforcing super to appear first, enforces that constructor bodies are executed in the correct order which would be: Object -> Parent -> Child -> ChildOfChild -> SoOnSoForth