Inheritance in Java

Site Admin · 11 Sep 2026 · 12 views

What Inheritance Does

Inheritance lets a new class (subclass) derive from an existing class (superclass) and automatically receive its fields and methods. You then add or override what is different. The keyword is extends.

Basic Example

class Vehicle {
    String brand;
    void start() { System.out.println(brand + " engine started"); }
}

class Car extends Vehicle {
    int doors;
    void honk() { System.out.println("Beep beep!"); }
}

Car myCar = new Car();
myCar.brand = "Hyundai";   // inherited field
myCar.start();             // inherited method
myCar.honk();              // own method

Method Overriding

A subclass can give an inherited method its own implementation. The @Override annotation tells the compiler you intend to override.

class Animal {
    void speak() { System.out.println("Some sound"); }
}
class Dog extends Animal {
    @Override
    void speak() { System.out.println("Woof"); }
}
class Cat extends Animal {
    @Override
    void speak() { System.out.println("Meow"); }
}

super Keyword

super refers to the superclass: call its constructor with super(...) and its methods with super.method().

class Car extends Vehicle {
    int doors;

    Car(String brand, int doors) {
        super();            // first statement: calls Vehicle()
        this.brand = brand;
        this.doors = doors;
    }
}

Types of Inheritance

  • Single: one class extends one class.
  • Multilevel: A -> B -> C, a chain of inheritance.
  • Hierarchical: many classes share one parent.

Java does not support multiple inheritance of classes (one class extending two classes). This ambiguity trap is avoided; interfaces provide a safe alternative.

Single inheritance

Multilevel inheritance

Hierarchical inheritance

Upcasting vs downcasting

Key Points

  • Subclasses inherit fields and methods and can override them.
  • super accesses superclass members and constructors.
  • No multiple inheritance of classes in Java.
Share this post:

Comments (0)

Please login or register to comment.