Inheritance: Superclass Constructors Tutorial

In my Superclass and Subclass Tutorial I discussed how subclasses inherit the members of a superclass. How does that apply to constructors? Well, constructors are not members, so the subclass doesn't inherit the superclass constructor(s). The subclass can invoke the superclass constructor(s) by using the super keyword. When the new operator initializes an object, it will invoke the proper constructor based on the number and type arguments being passed. The constructor in the subclass can pass its parameters on up the food chain to the superclass constructor. An example program is the best way to demonstrate this principle.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md SuperclassConstructors
C:\Java>cd SuperclassConstructors
C:\Java\SuperclassConstructors>Notepad SuperclassConstructors.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class SuperclassConstructors {
    public static void main(String args[]) {
        CardboardBox b1 = new CardboardBox(5, 5, 5, "inches", "brown");
        CardboardBox b2 = new CardboardBox(14, 17, 13, "centimeters", "white");

        System.out.println("Box #1 is a " + b1.color + " cardboard box with a volume of: " + b1.returnVolume() + " cubic " + b1.unitOfMeasurement);
        System.out.println("Box #2 is a " + b2.color + " cardboard box with a volume of: " + b2.returnVolume() + " cubic " + b2.unitOfMeasurement);
    }
}

class Box {
    int length = 0;
    int height = 0;
    int width = 0;
    String unitOfMeasurement = "";

    Box() {
        super();
    }

    Box(int length, int height, int width, String unitOfMeasurement) {
        this.length = length;
        this.height = height;
        this.width = width;
        this.unitOfMeasurement = unitOfMeasurement;
    }

    int returnVolume() {
        return (length * height * width);
    }
}

class CardboardBox extends Box {     
    String color=""; 
    
    CardboardBox() {
        super();
    }

    CardboardBox(int length, int height, int width, String unitOfMeasurement, String color ) {
        super(length, height, width, unitOfMeasurement);
        this.color = color;
    }
} 

Now switch back to the command prompt (CMD) and type in javac SuperclassConstructors.java and press Enter.
Now type in java SuperclassConstructors and press Enter.


C:\Java\SuperclassConstructors>javac SuperclassConstructors.java
C:\Java\SuperclassConstructors>java SuperclassConstructors
Box #1 is a brown cardboard box with a volume of: 125 cubic inches
Box #2 is a white cardboard box with a volume of: 3094 cubic centimeters


Final thoughts

In my next tutorial I will explore more functionality of the super keyword.


Tutorials