我被指示执行以下操作:
- 在 Carnivore 中创建一个不带参数的构造函数,调用 Animal 中的 super 构造函数。
Carnivore 是 Animal 的子类,Animal 是父类(super class)。所以我想在 Carnivore 中调用 Animal 的构造函数。这是代码:
动物父类(super class)
abstract public class Animal
{
int age;
String name;
String noise;
Animal(String name, int age)
{
this.age = age;
this.name = name;
}
Animal()
{
this("newborn", 0); //This is the super class that needs to be called in Carnivore.
}
}
食肉动物亚类
public class Carnivore extends Animal
{
Carnivore()
{
//Call Animal super constructor
}
}
我以前没有使用过继承,所以我仍在掌握它。感谢任何反馈,谢谢。
最佳答案
您可以使用super()
调用父类(super class)构造函数,如下所示:
public class Carnivore extends Animal {
Carnivore() {
super(); //calls Animal() no-argument constructor
}
}
With super(), the superclass no-argument constructor is called. With super(parameter list), the superclass constructor with a matching parameter list is called.
建议您引用here了解继承和super
的基础知识。
关于java - 如何从另一个继承类调用 super 构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40834704/