Subclass is a class that inherits from another class (the superclass).
It gains access to the fields and methods of the superclass and can override or extend them.

class Animal {
    void speak() {
        System.out.println("Animal sound");
    }
}
 
class Dog extends Animal { // subclass
    void bark() {
        System.out.println("Bark");
    }
}

Syntax

class SubclassName extends SuperclassName {
    // extra fields and methods
}

Key Capabilities od Subclass

  • Inherits all non-private members of superclass.
  • Can override methods from superclass.
  • Can add new fields and methods.
  • Can call superclass members using super.
  • Can be used for polymorphism.

Example with overriding

class Bird {
    void fly() {
        System.out.println("Bird is flying");
    }
}
 
class Eagle extends Bird {
    @Override
    void fly() {
        System.out.println("Eagle soars high");
    }
}

Real-World Analogy

A smartphone is a subclass of Phone. It inherits calling features, but also adds apps, camera and internet access.

Tip

Know how to:

  • use extends to create a subclass,
  • override superclass methods,
  • apply polymorphism: Animal a = new Dog(); a.speak();

Parent: _OOP