java为超类和子类传递参数?
我应该传递的值:
- 应保存所有仪器的名称和族
- 我们需要指定弦乐器是否使用弓
当我运行代码时,它会给我一个错误:“类字符串中的构造函数字符串不能应用于给定的类型
public class InstrumentTester
{
public static void main(String[] args)
{
/**
* Don't Change This Tester Class!
*
* When you are finished, this should run without error.
*/
Wind tuba = new Wind("Tuba", "Brass", false);
Wind clarinet = new Wind("Clarinet", "Woodwind", true);
Strings violin = new Strings("Violin", true);
Strings harp = new Strings("Harp", false);
System.out.println(tuba);
System.out.println(clarinet);
System.out.println(violin);
System.out.println(harp);
}
}
public class Instrument
{
private String name;
private String family;
public Instrument(String name, String family)
{
this.name = name;
this.family = family;
}
public String getName()
{
return name;
}
public String getFamily()
{
return family;
}
public void setName(String name)
{
this.name = name;
}
public void setFamily(String family)
{
this.family = family;
}
}
public class Strings extends Instrument
{
private boolean useBow;
public Strings(String name, String family, boolean useBow)
{
super(name, family);
this.useBow = useBow;
}
public boolean getUseBow()
{
return useBow;
}
public void setUseBow(boolean useBow)
{
this.useBow = useBow;
}
}
如果不接受参数族,如何传入参数族
# 1 楼答案
小提琴和竖琴在创建时不会传递家族名称,因此
Strings
构造函数不能将家族名称作为参数那么,你把什么传递给
super()
?如果所有字符串都属于同一个族,则可以硬编码该值。也许只是“字符串”:# 2 楼答案
这听起来像是在传递
family
,但类没有接受它。但事实是,您的类正在接受一个未传递的额外的family
参数根据
main
开头的注释,我的解释是您应该给所有Strings
一系列“字符串”。从Main
中的用法可以看出,只有2个参数传递给构造函数,这意味着Strings
构造函数不应该接受family
参数因此,构造函数应如下所示:
# 3 楼答案
将字符串定义为一个构造函数
但您尝试将其用作不同的参数:
您需要定义第二个构造函数或使用您创建的构造函数