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

标签 java constructor this

<分区>

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

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);  
    }   
}

我已经在 StackOverflow 上检查了很多关于这个主题的答案,但我仍然无法理解其中的原因。请用一些简单的例子和​​解释帮助我弄清楚这个错误。

最佳答案

如您所知,这是可行的:

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

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

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

关于java - 构造函数调用必须是构造函数中的第一条语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20198279/

相关文章:

c# - 在事件中使用 'this'

c# 下面构造函数中的两个 this 关键字有什么区别?

java - Android 6 棉花糖 ListView 。使用运行时权限启动 Activity

java - Maven 运行项目

java - 确保当构造函数抛出异常时最终变量被初始化

c++ - 如何在类构造后根据用户输入定义常量值

javascript - 试图将一个变量连接到一个 img 源中,但它忽略了该变量

java - 向现有产品类型添加新属性 - SAP Hybris e-Commerce

java - A*算法实现

c++ - 递归复制构造函数?