I have been instructed to do the following:
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.
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
.