gpt4 book ai didi

java - Java 中的构造函数链

转载 作者:行者123 更新时间:2023-12-01 06:38:36 26 4
gpt4 key购买 nike

Java 不是我的强项,所以请放轻松! :)

我正在尝试在下面的supersub类之间进行构造器链接

//父类(super class)

class Furniture{

String name;
int cost;
boolean IsAvlbl;

void Furniture(String name,int cost,boolean IsAvlbl){
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;

}
}

//子类

public class Table extends Furniture{


public Table(String name,int cost,boolean IsAvlbl)
{
super(name,cost,IsAvlbl);
}


public static void main(String args[])
{
Table t = new Table("dinning",2600,false);
t.runner();
}

void runner()
{
System.out.println("Name : "+this.name);
System.out.println("Cost : "+this.cost);
System.out.println("Is Avaiable : "+this.IsAvlbl);
}


}

弹出的错误是:

Table.java:20: error: constructor Furniture in class Furniture cannot be applied to given types;

    super(name,cost,IsAvlbl);
^ required: no arguments found: String,int,boolean

reason: actual and formal argument lists differ in length 1 error

我知道构造函数调用必须是第一行,并且参数必须相同......我尝试这样做,但错误仍然存​​在。

如果有人能告诉我为什么会出现此错误,我将不胜感激,因为我想了解其原因......尝试这种方式这种解决方案不是首选!

最佳答案

构造函数不会有任何返回类型

应该是这样的

Furniture(String name,int cost,boolean IsAvlbl){
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;

}

构造函数之前有 void 关键字,这使其成为一个方法。由于您有返回类型,java 在 Furniture 类中仅找到“无参数”(默认)构造函数,因此给出了编译错误。

关于java - Java 中的构造函数链,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23357252/

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