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

时间:2016-11-27 22:32:57

标签: java inheritance multiple-constructors

我已被指示执行以下操作:

  • 在Carnivore中创建一个没有参数的构造函数,在Animal中调用超级构造函数。

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

动物超类

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
}

}  

我之前没有继承过,所以我仍然没有掌握它。任何反馈都表示赞赏,谢谢。

1 个答案:

答案 0 :(得分:2)

您可以使用super()来调用超类构造函数,如下所示:

public class Carnivore extends Animal {

  Carnivore() {
    super(); //calls Animal() no-argument constructor
  }
}
  

使用super(),调用超类无参数构造函数。同   super(参数列表),具有匹配的超类构造函数   参数列表被调用。

我建议您推荐here以了解继承的基础知识和super

相关问题