Search⌘ K

Constructors of Subclasses

Explore how subclass constructors interact with superclass constructors in Java inheritance. Understand the use of the super keyword to initialize inherited fields, the importance of no-argument constructors, and the order of constructor calls in a class hierarchy.

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.

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

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 this purpose. ...