constructor call must be the
时间: 2023-04-24 13:06:03 浏览: 61
构造函数调用必须完成对象的初始化。在创建对象时,构造函数会被自动调用,以便对对象进行初始化操作。如果构造函数没有被正确调用,对象可能会处于未初始化的状态,导致程序出现错误。因此,构造函数调用是非常重要的一步。
相关问题
[{ "resource": "/D:/KY8_1.java", "owner": "_generated_diagnostic_collection_name_#2", "code": "1207959691", "severity": 8, "message": "Constructor call must be the first statement in a constructor", "source": "Java", "startLineNumber": 3, "startColumn": 10, "endLineNumber": 3, "endColumn": 21 }]
这个错误信息是因为在 KY8_1 类的构造函数中,调用了 `super(str)`,但是这个调用不是构造函数的第一条语句,而是在 `System.out.println("constructor of KY8_1");` 之后。
为了解决这个问题,你需要将 `super(str)` 移动到构造函数的第一条语句。修改后的代码如下:
```java
public class KY8_1 extends Thread {
public KY8_1(String str) {
super(str);
System.out.println("constructor of KY8_1");
}
public void run() {
for (int i = 0; i < 10; i++) {
System.out.println(i + " " + getName());
try {
sleep((int)(Math.random() * 1000));
} catch (InterruptedException e) {}
}
System.out.println("DONE! " + getName());
}
}
public class TwoThreadsTest {
public static void main (String[] args) {
new KY8_1("Go to Beijing??").start();
new KY8_1("Stay here!!").start();
}
}
```
现在,你可以重新编译并运行这个程序,这个错误应该就会消失了。
一直提示constructor+call+must+be+the+first+statement+in+a+constructor
这个错误提示是因为在构造函数中,构造函数调用必须是第一条语句。如果你在构造函数中的其他语句之前调用了构造函数,就会出现这个错误。解决这个问题的方法是将构造函数调用移动到构造函数的第一条语句。下面是一个示例代码,演示了如何正确地调用构造函数:
```java
public class MyClass {
private int myInt;
public MyClass(int myInt) {
this.myInt = myInt;
}
public MyClass() {
this(0); // 构造函数调用必须是第一条语句
}
}
```