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.
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.
Now let’s add the Dog class.
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. ...