Constructors of Subclasses
Follow the steps in this lesson to create an relation between a superclass and its subclass.
We'll cover the following...
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 instancesprivate int numOfLegs;private String color;// Constructorpublic void Animal(int numOfLegs, String color){this.numOfLegs = numOfLegs;this.color = color;}// Methodspublic 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
Java
Files
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. ...
Ask