gpt4 book ai didi

java - "Constructor call must be the first statement in a constructor"Java 代码中出现错误?

转载 作者:行者123 更新时间:2023-12-01 07:06:04 24 4
gpt4 key购买 nike

我在这段代码中遇到两个错误

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

  2. 隐式 super 构造函数 Parent() 未定义。必须显式调用另一个构造函数。

所以请帮我解决这些问题。

class Parent
{
public Parent(int x, int y,int z)
{
System.out.println("Created Parent");
}
}
public class Child extends Parent
{
Child(int x)// error 2
{

}
Child(int x, int y)// error 2
{
}
Child(int x, int y, int z)
{
this(x);
super(x,y,z);// error 2
System.out.println("Creating child");
this(x,y);// error 1
}
public static void main(String [] args)
{
Child c=new Child(1,2,3);
}
}

最佳答案

您需要了解四件事:

  • 如果您未指定任何显式构造函数调用,编译器会为您插入对 super() 的调用。

  • 任何构造函数都必须有恰好一个构造函数调用 - 显式或隐式 super() 调用。 (您的 Child(int, int, int) 构造函数中有三个。

  • 显式构造函数调用必须是构造函数主体中的第一个语句。

  • 您只能调用实际存在的构造函数 - 因此从 Child 调用 super() 会在 Parent 中查找无参数构造函数,不存在。

一种常见的模式是拥有一个“主”构造函数,同一类中的其他构造函数链接到该构造函数,然后该构造函数链接到父类(super class)。例如:

Child(int x)
{
this(x, 0); // Chains to the Child(int, int) constructor, defaulting y to 0
}

Child(int x, int y)
{
// Chains to the Child(int, int, int) constructor, defaulting z to 0
this(x, y, 0);
}

Child(int x, int y, int z)
{
super(x, y, z);
System.out.println("Creating child");
}

关于java - "Constructor call must be the first statement in a constructor"Java 代码中出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23760537/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com