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;
}
}
如果不接受参数族,我该如何传递?
解决方案
Strings violin = new Strings("Violin", true); Strings harp = new Strings("Harp", false);
小提琴和竖琴在创建时不会传递姓氏,因此Strings
构造函数不能期望一个作为参数。
public Strings(String name, boolean useBow)
那你传给什么super()
?如果所有字符串都属于同一个系列,那么您可以硬编码该值。也许只是“字符串”:
public Strings(String name, boolean useBow)
{
super(name, "String");
this.useBow = useBow;
}
推荐阅读
- jquery - Choices JS Re-Initialize 不适用于动态行添加
- powerbi - 如何在数据表 Power BI 中显示缺失的日期
- java - 列表遍历在 jsp 中不起作用,但当我只传递一个元素时工作正常
- python - 如果列 years >=10,则用户个人详细信息应替换为他的 id (pandas)
- python - 如何根据另一个值编辑列值?
- fpga - Libero FPGA 工具链中的“Qt:未测试的 Windows 6.2 版检测到错误消息”
- python - .loc 返回 Pandas 系列,而不是 GeoDataFrame。如何返回 GeoDataFrame
- atlassian-sourcetree - Sourcetree 分支未显示在侧边栏上
- python - 为什么opencv houghline检测到的线条与图像中的真实线条不平行?
- python-3.x - 基于总和为目标值的最接近组合连接两个数据帧