Java 执行所有子类';当超类只有一个带参数的构造函数时,带参数的s构造函数需要super(args)?

Java 执行所有子类';当超类只有一个带参数的构造函数时,带参数的s构造函数需要super(args)?,java,Java,我的困惑是,我已经用中的参数调用了超类的构造函数 class Animal{ String s; Animal(String s){ this.s = s; } } class Dog extends Animal{ Animal animal; Dog(String s) { super(s); } //here is an error "Implicit super co

我的困惑是,我已经用中的参数调用了超类的构造函数

class Animal{
    String s;
    Animal(String s){
        this.s = s;     
    }   
}


class Dog extends Animal{
    Animal animal;
    Dog(String s) {
        super(s);       
    }
    //here is an error "Implicit super constructor Animal() is undefined.Must explicitly invoke another constructor"
    Dog(Animal animal){
        this.animal = animal;       
    }   
}
但是为什么我仍然在另一个构造器狗(动物)中得到错误消息呢

在本例中,构造函数机制是如何工作的


谢谢

您的代码不正确。当
Dog
扩展
Animal
时,
Dog
不需要(也不应该有)一个
Animal
对象

正确的方法是

Dog(String s) {
    super(s);       
}

你的问题的答案很简单:是的


任何子类构造函数都必须首先调用super。如果超类只有一个接受某些参数的ctor,那么子类中的那些“超级调用”必须使用该ctor

那么您如何访问
动物
<代码>超级(s);s、 动物?在
Animal
上应该有返回所需内容的方法,例如
String get(){return s;}
在你的代码
isa
动物
中,我添加了一个setter和getter来演示如何访问super的字段扫描你解释为什么狗不能拥有动物对象。@ScaryWombat:如果你想在动物之间建立关联,那么你真的需要这样的模式,狗与任何有某种关系的动物都有联系,比如说敌人(猫),那么我们就需要有这种关系。正如ScaryWombat所说,你可能不想要
狗(动物)
构造器。然而,我想纠正另一个错误。一个类很可能有两个或多个构造函数。但是,当创建一个对象时,只调用一个构造函数,而不是两个。因此,按照您编写的方式,当其他代码显示“new Dog”时,它会调用带有字符串参数的代码或带有动物参数的代码。不是两者都有(除非你告诉一个构造函数调用另一个)。所以你的说法“我已经调用了超类的构造函数…”是错误的。我认为你从根本上误解了构造函数的工作原理,尤其是在子类中,你应该回去学习关于这个主题的教程。@ajb谢谢你,你的回答真的很有帮助:-)谢谢你的回答:-)非常欢迎你;感谢您的快速接受!
class Animal{
    String s;
    Animal(String s){
        this.s = s;     
    }  

    // add a setter and getter
    public String getS () {return s;}
    public void setS (String s) {this.s = s;} 
}


class Dog extends Animal{
    Dog(String s) {
        super(s);       
    }
}