Java 构造函数调用必须是构造函数中的第一条语句

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20198279/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 00:12:34  来源:igfitidea点击:

Constructor call must be the first statement in a constructor

javaconstructorthis

提问by beginner

I do not understand why the below code displays the error Constructor call must be the first statement in a constructorif I shift this(1);to the last line in the constructor.

Constructor call must be the first statement in a constructor如果我this(1);移到构造函数的最后一行,我不明白为什么下面的代码会显示错误。

package learn.basic.corejava;

public class A {
    int x,y;

    A()
    {     
        // this(1);// ->> works fine if written here
        System.out.println("1");
        this(1);  //Error: Constructor call must be the first statement in a constructor
    }

    A(int a)
    {
        System.out.println("2");
    }

    public static void main(String[] args) { 
        A obj1=new A(2);  
    }   
}

I've checked many answers on this topic on StackOverflow but I still could not understand the reason for this. Please help me to make clear about this error with some easy example and explanation.

我已经在 StackOverflow 上检查了很多关于这个主题的答案,但我仍然无法理解这样做的原因。请通过一些简单的示例和解释帮助我澄清此错误。

采纳答案by óscar López

As you know, this works:

如您所知,这有效:

A() {
      this(1);
      System.out.println("1");
}

Why? because it's a rule of the language, present in the Java Language Specification: a call to another constructor in the same class (the this(...)part) or to a constructor in the super class (using super(...)) must go in the first line. It's a way to ensure that the parent's state is initialized beforeinitializing the current object.

为什么?因为它是语言的规则,出现在 Java 语言规范中:对同一类(this(...)部分)中的另一个构造函数或超类(using super(...))中的构造函数的调用 必须放在第一行。这是一种确保初始化当前对象之前初始化父级状态的方法。

For more information, take a look at this post, it explains in detail the situation.

有关更多信息,请查看此帖子,它详细说明了情况。

回答by T I

The error tells you the problem

错误告诉你问题

A()
{     
      System.out.println("1");
      this(1);  //Error: Constructor call must be the first statement in a constructor
}

i.e. you must call the constructor first

即您必须先调用构造函数

A()
{
      this(1);
      System.out.println("1");
}

this also applies to calls to super

这也适用于调用 super

class B extends A
{
    B()
    {
        super();
        System.out.println("1");
    }
}

the reason being is answered here

原因在这里得到了回答