简体   繁体   English

编写一个 Dog 构造函数,它有一个参数,即名称,并调用超级构造函数并传递名称和动物类型“狗”。 不能通过类型

[英]Write a Dog constructor that has one argument, the name, and calls the super constructor passing it the name and the animal type “dog”. cant pass type

public class Pet
{
    private String name;
    private String type;

    public Pet(String n, String t)
    {
        name = n;
        type = t;
    }
    public String getType(){
        return type;
    }
    public String getName(){
        return name;
    }

    public void speak()
    {
        System.out.println("grr!");
    }
    public static void main(String[] args)
    {
        Pet p = new Pet("Sammy","hamster");
        System.out.println(p.getType());
        p.speak();

        Dog d = new Dog("Fido");
        System.out.println(d.getType());
        d.speak();
        //Cat c = new Cat("Fluffy");
        //System.out.println(c.getType());
        //c.speak();
    }
}
class Dog extends Pet
{
    public Dog(String name){
        super(name);
    }
    public void speak(){
        System.out.println("Woof");
    }
}
// Add a Cat class

How do I add "type" to this without adding another String to my parameter?如何在不向参数中添加另一个字符串的情况下向其添加“类型”? I've tried other ways that obviously didn't work but I still tried anyway.我尝试了其他显然不起作用的方法,但我仍然尝试过。 So how do I add another object to my super class from Pet without adding more to my parameter?那么如何从 Pet 添加另一个对象到我的超类而不向我的参数添加更多?

Constructor with one parameter for the dog class:带有狗类的一个参数的构造函数:

 public Dog(String name) {
    super(name, "dog");
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 是否可以使用类型参数 List 覆盖继承的方法<animal>与列表<dog> ?</dog></animal> - Is it possible to override an inherited method with type parameter List<Animal> with List<Dog>? 类型不匹配:无法从地图转换 <String,List<Animal> &gt;到地图 <String,List<Dog> &gt; - Type mismatch: cannot convert from Map<String,List<Animal>> to Map<String,List<Dog>> 如何将多字狗名计为一个记号 - How to make a multiple word dog name count as one token 将List <Animal>转换为List <Dog> - Casting List<Animal> to List<Dog> 为什么它说 class dog 中的构造函数 dog 不能应用于给定类型? 它似乎运行但抛出错误,这是为什么呢? - Why does it say constructor dog in class dog cannot be applied to given types? It seems to run but throws an error, why is that? 我可以调用超级构造函数并在java中传递类名吗? - Can I call the Super Constructor and pass the Class name in java? 泛型类型参数构造函数 - Generic type argument constructor 我可以在构造函数中传递多个Super调用吗? - Can I pass multiple Super calls in a constructor? java对象,我用动物speedy = new dog()创建动物或狗吗? 为什么? - java objects, do I create an animal or a dog with animal speedy = new dog(); and why? 狗是动物,但清单 <Dog> 没有列出 <Animal> 。 如何在泛型/多态函数中安全使用它? - Dog is Animal but list<Dog> is not list<Animal>. How to use it safely in a generic/polymorphic function?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM