如何从另一个继承的 class 调用超级构造函数?

How to call a super constructor from another inherited class?

我被指示执行以下操作:

Carnivore 是 Animal 的子 class,Animal 是超级 class。所以我希望在 Carnivore 中调用 Animal 中的构造函数。这是代码:

动物超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.
}

}

肉食亚class

public class Carnivore extends Animal
{

   Carnivore()
{
   //Call Animal super constructor
}

}  

我以前没有接触过继承,所以我仍在努力掌握它。感谢任何反馈,谢谢。

您可以使用 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