← Chapter 6 — Object-Oriented Programming

25. Inheritance & super Keyword

mixed

Description

Inheritance lets one class reuse and extend another class. A child class uses extends to inherit accessible fields and methods from its parent.

The super keyword refers to the parent part of the current object. Use it to call a parent constructor or deliberately reuse a parent method.

Subtopics

Extending a class

Description

A child class inherits from one parent class.

Explanation

Use inheritance only for a genuine is-a relationship.

Example

class GraduateStudent extends Student { }

Calling super

Description

super can call the parent constructor.

Explanation

It must be the first statement in a child constructor.

Example

super(name);

Explanation

Java supports single class inheritance: a class has one direct parent. It can still implement multiple interfaces, which often provides a flexible alternative.

Example

public class InheritanceDemo {
    static class Student {
        String name;
        Student(String name) { this.name = name; }
    }
    static class GraduateStudent extends Student {
        GraduateStudent(String name) { super(name); }
    }
    public static void main(String[] args) {
        System.out.println(new GraduateStudent("Rohan").name);
    }
}

Key points

  • extends creates inheritance.
  • super refers to the parent class.
  • A child can reuse parent behavior.

Open reference