有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

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

如果不接受参数族,如何传入参数族


共 (3) 个答案

  1. # 1 楼答案

    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;
    }
    
  2. # 2 楼答案

    How do I pass in the parameter family if it doesn't take it?

    这听起来像是在传递family,但类没有接受它。但事实是,您的类正在接受一个未传递的额外的family参数

    根据main开头的注释,我的解释是您应该给所有Strings一系列“字符串”。从Main中的用法可以看出,只有2个参数传递给构造函数,这意味着Strings构造函数不应该接受family参数

    因此,构造函数应如下所示:

    public Strings(String name, boolean useBow)
    {
        super(name, "Strings"); // note that I replaced family with "Strings"
        this.useBow = useBow;
    }
    
  3. # 3 楼答案

    将字符串定义为一个构造函数

    public Strings(String name, String family, boolean useBow)
    

    但您尝试将其用作不同的参数:

    Strings violin = new Strings("Violin", true);
    

    您需要定义第二个构造函数或使用您创建的构造函数