Inheritance Example in Java

Inheritance is one of the four pillars of Object-Oriented Programming (OOP) in Java. It allows a child class (subclass) to inherit the fields and methods of a parent class (superclass) using the extends keyword. This promotes code reuse, establishes an “is-a” relationship between classes, and forms the foundation for runtime polymorphism. In this post we walk through a practical example of single-level inheritance where a Box class extends a Rectangle class — reusing area logic while adding volume calculation on top of it.

The Code


import java.io.*;

// Parent class: represents a 2D rectangle
class Rectangle {
    int length;  // length of the rectangle
    int width;   // width of the rectangle

    // Constructor initialises length and width
    Rectangle(int length, int width) {
        this.length = length;
        this.width  = width;
    }

    // Returns the area of the rectangle (length x width)
    public int calculateArea() {
        return length * width;
    }
}

// Child class: extends Rectangle to represent a 3D box
class Box extends Rectangle {
    int height;  // the additional dimension that makes it a 3D box

    // Constructor chains to Rectangle via super() to initialise
    // the inherited length and width, then sets its own height
    Box(int length, int width, int height) {
        super(length, width);   // call Rectangle's constructor
        this.height = height;
    }

    // Returns the volume of the box (length x width x height)
    // Note: length and width are inherited from Rectangle
    public int calculateVolume() {
        return length * width * height;
    }
}

// Driver class
class BoxDemo {
    public static void main(String args[]) throws IOException {
        BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));

        System.out.println("Enter length of box:");
        int length = Integer.parseInt(reader.readLine());

        System.out.println("Enter width of box:");
        int width = Integer.parseInt(reader.readLine());

        System.out.println("Enter height of box:");
        int height = Integer.parseInt(reader.readLine());

        // A Box object has access to methods from both Rectangle and Box
        Box box = new Box(length, width, height);

        System.out.println("Base Area = " + box.calculateArea());   // inherited
        System.out.println("Volume    = " + box.calculateVolume()); // own method
    }
}

How the Code Works

Here is a step-by-step walkthrough of the example above:

  1. Parent class Rectangle — Declares two int fields, length and width. Its constructor initialises both, and calculateArea() returns their product.
  2. Child class Box extends Rectangle — The extends keyword makes Box a subclass of Rectangle. Every Box object automatically inherits length, width, and calculateArea() from the parent.
  3. Constructor chaining with super() — Inside Box‘s constructor, super(length, width) calls the parent constructor to initialise the inherited fields. Only after this does Box set its own height field.
  4. calculateVolume() — A method defined only in Box. It uses the inherited length and width fields together with its own height to compute the result.
  5. Driver class BoxDemo — Reads three integers from the user, creates a Box object, then calls both calculateArea() (inherited from Rectangle) and calculateVolume() (defined in Box) on the same object.

Sample Input / Output

Enter length of box:
5
Enter width of box:
10
Enter height of box:
7
Base Area = 50
Volume    = 350

Output Explanation

  1. The program reads length = 5, width = 10, and height = 7 from the user.
  2. calculateArea() returns 5 × 10 = 50. This method is defined in Rectangle but is called on a Box object — this is inheritance in action.
  3. calculateVolume() returns 5 × 10 × 7 = 350. It accesses the parent’s length and width fields directly, demonstrating that the child class shares the parent’s state.

See Also

Conclusion

Inheritance in Java lets a child class build on top of a parent class — reusing its data and behaviour while adding or extending what it needs. The extends keyword establishes the relationship, and super() provides clean access to the parent constructor. Mastering inheritance is essential because it also underpins runtime polymorphism, where a parent reference can point to child objects and dispatch method calls dynamically at run time.

What is inheritance in Java?

Inheritance is a mechanism in Java where one class (subclass) acquires the fields and methods of another class (superclass) using the extends keyword. It models “is-a” relationships — a Box is a Rectangle — and eliminates the need to duplicate common code across related classes.

What is the difference between single and multilevel inheritance?

Single inheritance means one class directly extends one parent (e.g., Box extends Rectangle). Multilevel inheritance forms a chain — for example, Class C extends Class B, and Class B extends Class A. Java supports both. It does not, however, allow a class to extend more than one class at a time (multiple inheritance through classes is not supported).

What does super() do in a child class constructor?

super() invokes the constructor of the immediate parent class. It must always be the very first statement in the child constructor. If the parent class has no default (no-arg) constructor and you omit an explicit super() call, the compiler reports an error. It is the standard way to initialise inherited fields that are declared in the parent.

Can a subclass access private members of the superclass?

No. Private members of a superclass are not directly accessible in a subclass. You need to use public or protected getter and setter methods defined in the parent to work with them. This encapsulation boundary is intentional — inheritance provides code reuse, not unlimited access to internal state.

Does Java support multiple inheritance?

Java does not allow a class to extend more than one class, which avoids the “diamond problem” seen in languages like C++. However, a class can implement multiple interfaces, which achieves a similar composition of behaviour. From Java 8 onwards, interfaces can also contain default method implementations, giving you much of the power of multiple inheritance without the ambiguity.

Further Reading

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.