Harry Harry - 10 days ago 8
Java Question

How to call a super constructor from another inherited class?

I have been instructed to do the following:


  • Create a constructor with no arguments in Carnivore that call the super constructor in Animal.



Carnivore is a sub class of Animal which is the super class. so I am looking to call the constructor in Animal within Carnivore. Here is the code:

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.
}

}


Carnivore sub-class

public class Carnivore extends Animal
{

Carnivore()
{
//Call Animal super constructor
}

}


I haven't worked with inheritance before so I'm still getting to grips with it. Any feedback is appreciated, thanks.

Answer

You can use super() to call super class constructor as shown below:

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.

I recommend you to refer here to understand the basics of inheritance and super.