Java中的构造函数转换
Java不是我的强项套件,所以请放轻松!:) 我正在尝试在下面的Java中的构造函数转换,java,class,Java,Class,Java不是我的强项套件,所以请放轻松!:) 我正在尝试在下面的super和sub类之间进行构造或链接 //超类 class Furniture{ String name; int cost; boolean IsAvlbl; void Furniture(String name,int cost,boolean IsAvlbl){ this.name = name; this.cost = cost;
super
和sub
类之间进行构造或链接
//超类
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);
}
}
//子类
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:错误:类家具中的构造函数家具不能应用于给定类型
super(name,cost,IsAvlbl);
^ required: no arguments found: String,int,boolean
原因:实际参数列表和形式参数列表的长度不同1错误
我知道构造函数调用必须是第一行,参数必须相同……我尝试过这样做,但错误持续存在
如果有人能告诉我为什么会出现这个错误,我将不胜感激,因为我想了解它的原因。。。。。尝试这种方式,这种解决方案不是首选 构造函数将没有任何返回类型 应该是
Furniture(String name,int cost,boolean IsAvlbl){
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;
}
构造函数前面有
void
关键字,这使它成为一种方法。由于您有返回类型,java在Furniture
类中只找到了“无参数”(默认)构造函数,因此给出了编译错误。在java中,构造函数不应该有返回类型。从家具中删除void
Furniture(String name,int cost,boolean IsAvlbl){
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;
}
void家具(字符串名称、int成本、布尔值isavbl){//Method
是一个方法而不是构造函数。
替换为:
家具(字符串名,整型成本,布尔ISAVBL){//Constructor
Furniture(String name,int cost,boolean IsAvlbl){
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;
}
请记住,构造函数没有返回类型。。有趣的是,您可以使用类名(类似于构造函数)定义方法,但唯一的区别是,方法将具有返回类型。void Furniture()
不是构造函数。它在Furniture
类中被视为方法
public Furniture()
是正确的语法,因为构造函数没有任何返回类型
public Furniture(String name, int cost, boolean IsAvlbl) {
this.name = name;
this.cost = cost;
this.IsAvlbl = IsAvlbl;
}
该死……超级蠢,我知道区别,但我从未在代码中发现它!!!:)