首页 > 解决方案 > 传递超类和子类的参数?

问题描述

我应该传入的值:

当我运行我的代码时,它给了我错误:“类字符串中的构造函数字符串不能应用于给定类型;”

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;
    }
}

如果不接受参数族,我该如何传递?

标签: java

解决方案


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;
}

推荐阅读