java - 传递父类(super class)和子类的参数?

标签 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);

fiddle 和竖琴在创建时不会传递姓氏,因此 Strings 构造函数不能期望将姓氏作为参数。

public Strings(String name, boolean useBow)

那么你将什么传递给 super() 呢?如果所有字符串都属于同一个系列,那么您可以对该值进行硬编码。也许只是“字符串”:

public Strings(String name, boolean useBow)
{
    super(name, "String");
    this.useBow = useBow;
}

关于java - 传递父类(super class)和子类的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60762350/

相关文章:

java - 用 Java 实现中断服务例程

java - Object 类的方法如何通过接口(interface)可见?

java - FTP 客户端类未连接

Java 8 流 - 查找 Map<String, List<Object>> 的最大计数值

java - Java 8 中的 PriorityBlockingQueue 流乱序

java - Derby 嵌入式数据库中的查询

Javafx:使用 FXML 的可重用集合

java - 奇怪的问题 : jsf inside jsp not working

java - : "JPA Facet File Change Event Handler" 期间发生内部错误

java - 打乱字符串以便没有对象位于其原始位置