Contact Form

Name

Email *

Message *

Search This Blog

Image

Implementation of Inheritance in JAVA

Inheritance lets one class reuse the fields and methods of another. Instead of copying code, you build a new class on top of an existing one and add or change only what is different. It is one of the four core ideas of object-oriented programming in Java, alongside encapsulation, polymorphism and abstraction.

In this tutorial you will learn the vocabulary, how extends and super work, and each type of inheritance Java supports, with complete programs and the output each one produces.

Key terms

  • Superclass (parent or base class): the class whose members are inherited.
  • Subclass (child or derived class): the class that inherits from the superclass using extends.
  • extends: the keyword that creates the inheritance relationship.
  • super: a keyword that refers to the superclass, used to call its constructor or methods.

A common mix-up is calling the parent the "derived" class. It is the other way around: the child is derived from the parent.

The relationship follows the "is-a" rule. A BedRoom is a Room, so it makes sense for BedRoom to extend Room. If the sentence sounds wrong ("a Car is an Engine"), inheritance is the wrong tool, and you probably want composition instead.

1. Single inheritance

One subclass extends one superclass. Here BedRoom inherits length, breadth and area() from Room and adds a height and a volume() method.

class Room {
    int length;
    int breadth;

    Room(int x, int y) {
        length = x;
        breadth = y;
    }

    int area() {
        return length * breadth;
    }
}

class BedRoom extends Room {
    int height;

    BedRoom(int x, int y, int h) {
        super(x, y);   // calls the Room constructor
        height = h;
    }

    int volume() {
        return length * breadth * height;
    }
}

public class InherTest {
    public static void main(String[] args) {
        BedRoom room1 = new BedRoom(10, 20, 30);
        System.out.println("Area = " + room1.area());      // inherited from Room
        System.out.println("Volume = " + room1.volume());  // defined in BedRoom
    }
}

Output

Area = 200
Volume = 6000

Notice super(x, y) is the first line of the BedRoom constructor. Java requires that a call to the superclass constructor comes first. If you leave it out, Java inserts super() automatically, and the code will not compile if Room has no no-argument constructor.

2. Multilevel inheritance

A class extends a class that itself extends another, forming a chain: Home to Room to BedRoom. The last class in the chain has everything from all the classes above it.

class Home {
    int length;
    int breadth;

    Home(int x, int y) {
        length = x;
        breadth = y;
    }

    int area() {
        return length * breadth;
    }
}

class Room extends Home {
    int height;

    Room(int x, int y, int h) {
        super(x, y);
        height = h;
    }

    int volume() {
        return length * breadth * height;
    }
}

class BedRoom extends Room {
    BedRoom(int x, int y, int h) {
        super(x, y, h);
    }

    void type() {
        System.out.println("Sleeping");
    }
}

public class MultilevelTest {
    public static void main(String[] args) {
        BedRoom room1 = new BedRoom(10, 20, 30);
        System.out.println("Area = " + room1.area());      // from Home
        System.out.println("Volume = " + room1.volume());  // from Room
        room1.type();                                       // from BedRoom
    }
}

Output

Area = 200
Volume = 6000
Sleeping

3. Hierarchical inheritance

One superclass has two or more subclasses. Each child inherits the same parent members but adds its own behaviour. This is the reverse of what many beginners expect: it is one parent, many children.

class Room {
    int length;
    int breadth;

    Room(int x, int y) {
        length = x;
        breadth = y;
    }

    int area() {
        return length * breadth;
    }
}

class BedRoom extends Room {
    int height;

    BedRoom(int x, int y, int h) {
        super(x, y);
        height = h;
    }

    int volume() {
        return length * breadth * height;
    }
}

class DrawingRoom extends Room {
    int height;

    DrawingRoom(int x, int y, int h) {
        super(x, y);
        height = h;
    }

    int volume() {
        return length * breadth * height;
    }
}

public class HierarchicalTest {
    public static void main(String[] args) {
        BedRoom bed = new BedRoom(10, 20, 30);
        System.out.println("Bed Room - Area = " + bed.area() + ", Volume = " + bed.volume());

        DrawingRoom drawing = new DrawingRoom(20, 30, 30);
        System.out.println("Drawing Room - Area = " + drawing.area() + ", Volume = " + drawing.volume());
    }
}

Output

Bed Room - Area = 200, Volume = 6000
Drawing Room - Area = 600, Volume = 18000

Both child classes repeat the height field and volume() method here. When you see duplicated members like that, it is usually a sign they belong in the superclass or in a shared intermediate class.

4. Multiple inheritance (through interfaces)

Java does not allow a class to extend more than one class. This avoids the "diamond problem," where two parents define the same method and the compiler cannot tell which to use. You can still combine behaviour by extending one class and implementing any number of interfaces.

class Student {
    int rollNumber;

    void getNumber(int n) {
        rollNumber = n;
    }

    void putNumber() {
        System.out.println("Roll Number : " + rollNumber);
    }
}

class Test extends Student {
    float part1, part2;

    void getMarks(float m1, float m2) {
        part1 = m1;
        part2 = m2;
    }

    void putMarks() {
        System.out.println("Marks Obtained");
        System.out.println("Part 1 = " + part1);
        System.out.println("Part 2 = " + part2);
    }
}

interface Sports {
    float SPORT_WT = 6.0F;   // interface fields are public static final
    void putWT();
}

class Results extends Test implements Sports {
    float total;

    public void putWT() {
        System.out.println("Sports WT = " + SPORT_WT);
    }

    void display() {
        total = part1 + part2 + SPORT_WT;
        putNumber();
        putMarks();
        putWT();
        System.out.println("Total Score = " + total);
    }
}

public class MultipleInheritanceTest {
    public static void main(String[] args) {
        Results student1 = new Results();
        student1.getNumber(4321);
        student1.getMarks(29.5F, 30.5F);
        student1.display();
    }
}

Output

Roll Number : 4321
Marks Obtained
Part 1 = 29.5
Part 2 = 30.5
Sports WT = 6.0
Total Score = 66.0

Here Results inherits implementation from Test (and through it, Student), and it promises to provide the behaviour required by the Sports interface. An interface method must be declared public in the implementing class, which is why putWT() has that modifier.

Method overriding

A subclass can replace an inherited method with its own version. Use the @Override annotation so the compiler warns you if the signature does not actually match.

class Room {
    String describe() {
        return "A generic room";
    }
}

class BedRoom extends Room {
    @Override
    String describe() {
        return "A room for sleeping";
    }
}

Calling describe() on a BedRoom object returns "A room for sleeping", even if the variable is declared as type Room. This is runtime polymorphism. Inside the overriding method you can still reach the parent version with super.describe().

Things to remember

  • Constructors are not inherited. A subclass must call a superclass constructor, explicitly with super(...) or implicitly.
  • Private members are not accessible in subclasses. They exist in the object but can only be reached through public or protected methods of the superclass.
  • A final class cannot be extended and a final method cannot be overridden. String is a well-known final class.
  • Every class extends Object if you do not name a superclass, which is where methods like toString() and equals() come from.
  • Prefer composition when the "is-a" test fails. Deep inheritance chains make code harder to change.

Practice exercises

  1. Create a Shape superclass with an area() method and subclasses Circle and Rectangle that override it.
  2. Extend the multilevel example so BedRoom overrides area() and calls super.area() inside it.
  3. Write an interface Printable and make two unrelated classes implement it.

Summary

Java supports single, multilevel and hierarchical inheritance between classes, and achieves multiple inheritance of behaviour through interfaces. Remember the direction of the relationship: subclasses extend superclasses, and super reaches back up. Next, try learning about abstract classes and interfaces in more depth, which build directly on these ideas.

Comments