9.2 Calling the Superclass Constructor

A subclass can have its own private data members, so a subclass can also have its own constructors.

The constructors of the subclass can initialize only the instance variables of the subclass. Thus, when a subclass object is instantiated the subclass object must also automatically execute one of the constructors of the superclass.

To call a superclass constructor the super keyword is used. The following example programs demonstrate use of super keyword.

inheritance-constructor

(Rectangle.java)

/**
 *  This class holds data of a Rectangle.
 */

public class Rectangle
{
   private double length;  // To hold length of rectangle
   private double width;  // To hold width of rectangle

   /**
    *  The constructor initialize rectangle's 
    *  length and width with default value    
    */

   public Rectangle()
   {
      length = 0;
      width = 0;
   }

   /**
    *  The constructor accepts the rectangle's  
    *  length and width.   
    */

   public Rectangle(double length, double width)
   {
      this.length = length;
      this.width = width;
   }

   /**
    *  The getArea method returns the area of 
    *  the rectangle.
    */

   public double getArea()
   {
      return length * width;
   }
}

(Box.java)

/**
 *  This class holds data of a Box.
 */

public class Box extends Rectangle
{
   private double height;  // To hold height of the box

   /**
    *  The constructor initialize box's 
    *  length, width and height with default value.  
    */

   public Box()
   {
      // Call the superclass default constructor to
      // initialize length and width.
      super();
      //Initialize height.
      height = 0;
   }

   /**
    *  The constructor accepts the box's  
    *  length, width and height.   
    */

    public Box(double length, double width, double height)
    {
      // Call the superclass constructor to
      // initialize length and width.
      super(length, width);
      
      // Initialize height.
      this.height = height;
   }

   /**
    *  The getVolume method returns the volume of 
    *  the box.
    */

   public double getVolume()
   {
      return getArea() * height;
   }
}

(BoxDemo.java)

/**
 * This program demonstrates calling
 * of superclass constructor.
 */

public class BoxDemo
{
   public static void main(String[] args)
   {
      // Create a box object.
      Box myBox1 = new Box();

      // Display the volume of myBox1.
      System.out.println("Volume: " + myBox1.getVolume());

      // Create a box object.
      Box myBox2 = new Box(12.2, 3.5, 2.0);

      // Display the volume of myBox2.
      System.out.println("Volume: " + myBox1.getVolume());
   }
}