Constructors of Subclasses

Follow the steps in this lesson to create an relation between a superclass and its subclass.

Interaction between classes

Subclasses inherit all the instance variables and methods of a superclass which they extend. However, the constructor of a superclass cannot be inherited. Let’s implement the Animal's hierarchy. Look at the code below.

Press + to interact
public class Animal
{
// Private instances
private int numOfLegs;
private String color;
// Constructor
public void Animal(int numOfLegs, String color)
{
this.numOfLegs = numOfLegs;
this.color = color;
}
// Methods
public void eat()
{
System.out.println("Time to eat.");
}
public void sleep()
{
System.out.println("Time to sleep.");
}
}

Now let’s add the Dog class.

Press + to interact
Animal.java
Dog.java
public class Dog extends Animal
{
public static void bark()
{
System.out.println("Bark!");
}
}

Look at line 1 in Dog.java. We extend the Animal class when writing the header of the Dog class. In it, we implement the bark() method, which prints Bark on the screen.

Now suppose we have to make an object of the Dog class. How are we going to set the numOfLegs and color inherited from the Animal class? A specially designed Dog constructor will serve ...