9.1 What is inheritance?

Inheritance is the mechanism that allows programmers to create new classes from existing class. By using inhertitance programmers can re-use code they've already written.

Any new class that you create from an existing class is called sub class; existing class is called super class.

The sub class gets all of the methods and state variables of the super class by default. The sub class can add new methods and state variables. The sub class can also redefine methods and state variables of its parent.

Let's understand these concept by an example :

inheritance

The following rules about superclasses and subclasses should be kept in mind:

  • All data members of the superclass are also data members of the subclass. Similarly, the methods of the superclass are also the methods of the subclass.
  • The private members of the superclass cannot be accessed by the members of the subclass directly.
  • The subclass can directly access the public members of the superclass.

Following program illustrate this :

(Rectangle.java)

/**
 * Rectangle class using as super class.
 */
public class Rectangle
{
   private double length;  //To hold length
   private double width;   //To hold width

   /**
    * Sets length and width of rectangle
    */
   public void setRectangle(double length, double width)
   {
      this.length = length;
      this.width  = width;
   }
 
   /**
    * Returns area of rectangle
    */
   public double getArea()
   {
      return length * width;
   }
}

(Box.java)

/**
 * The class Box extending Rectangle class.
 */
public class Box extends Rectangle
{
   private double height;  //To hold height

   /**
    * Sets length, width and heigth of box
    */
   public void setBox(double length, double width, double height)
   {
      // Call the inherited setRectangle method
      // to set length and width of box. 
      setRectangle(length,width); 
      this.height = height;
   }
 
   /**
    * Returns volume of cube
    */
   public double getVolume()
   {
      //Call the inherited getArea method
      return getArea() * height;
   }
}

(BoxDemo.java)

/**
 *  This program demonstrates the Box class, which 
 *  inherits from the Rectangle class.  
 */
public class BoxDemo
{
   public static void main(String[] args)
   {
      // Create a Box object.
      Box room = new Box();

      // Set values in Box object.
      room.setBox(12.5, 10.5, 9.5);
      
      // Display the volume.
      System.out.println("Volume is " + room.getVolume());
   }
}

Output :

Volume is 1246.875