Skip to content

Inheritance

🔷 What is Inheritance?

Inheritance is a mechanism in Java where one class (child/subclass/derived class) acquires the properties (fields) and behaviors (methods) of another class (parent/superclass/base class).

It allows code reusability and establishes a relationship between classes.


Why Use Inheritance?

  • Reusability: Avoid rewriting common code by inheriting it.
  • Extensibility: You can add new features to existing classes.
  • Method Overriding: Customize or modify behavior of inherited methods.
  • Polymorphism: Subclasses can be treated as their parent class type, enabling flexible code.

Basic Terminology

Term Description
Superclass The class whose properties are inherited (parent class).
Subclass The class that inherits from the superclass (child class).
extends Keyword used to declare inheritance.

Syntax

class Superclass {
    // fields and methods
}

class Subclass extends Superclass {
    // additional fields and methods
}

Example

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    void sound() {
        System.out.println("Dog barks");
    }
}

public class TestInheritance {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.sound();  // Output: Dog barks

        Animal a = new Animal();
        a.sound();  // Output: Animal makes a sound
    }
}
  • Dog inherits from Animal.
  • It overrides the sound() method.

Types of Inheritance in Java

  1. Single Inheritance One class inherits from another class. class B extends A {}

  2. Multilevel Inheritance Chain of inheritance where class C inherits from B, and B inherits from A. class C extends B {}, class B extends A {}

  3. Hierarchical Inheritance Multiple classes inherit from a single class. class B extends A {}, class C extends A {}


Note: Multiple Inheritance (with Classes) is NOT supported in Java!

  • Java does not allow multiple inheritance with classes to avoid ambiguity.
  • However, Java supports multiple inheritance of types using interfaces.

Method Overriding

  • Subclass can provide a specific implementation of a method already defined in superclass.
  • The method signature must be the same.
  • Helps achieve runtime polymorphism.

Example:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Cat meows");
    }
}

The super Keyword

  • Used to refer to superclass members (variables, methods, constructors).
  • Useful to access overridden methods or superclass constructors.

Example:

class Animal {
    void sound() {
        System.out.println("Animal sound");
    }
}

class Dog extends Animal {
    void sound() {
        super.sound();  // calls Animal's sound method
        System.out.println("Dog barks");
    }
}

Inheritance and Constructors

  • Constructors are not inherited.
  • Subclass constructor calls superclass constructor using super().
  • If not explicitly called, the default no-arg superclass constructor is called automatically.

Summary Table:

Feature Description
Keyword extends
Inheritance Type Single, Multilevel, Hierarchical
Multiple inheritance Not allowed with classes; allowed with interfaces
Access to members Subclass inherits accessible members (private not accessible directly)
Overriding Subclass can override superclass methods
Constructors Not inherited; called using super()
Purpose Code reuse, polymorphism, extensibility

Method Overriding


🔷 What is Method Overriding?

Method overriding occurs when a subclass (child class) provides its own implementation of a method that is already defined in its superclass (parent class). The method in the subclass has the same name, return type, and parameters as the one in the superclass.


Why use Method Overriding?

  • To modify or extend the behavior of an inherited method.
  • Supports runtime polymorphism (dynamic method dispatch).
  • Allows a subclass to provide specific behavior while keeping the same method signature.

Rules for Method Overriding

Rule Explanation
Method name and parameters must be identical The overriding method must have the same name and parameter list.
Return type must be the same or covariant Return type should be same or a subtype (covariant return).
Access level cannot be more restrictive If superclass method is public, subclass cannot make it private.
Overriding method can throw fewer or narrower exceptions It cannot throw broader checked exceptions than the overridden method.
final methods cannot be overridden Methods declared final in superclass cannot be overridden.
Static methods cannot be overridden Static methods are hidden, not overridden.

Example of Method Overriding

class Animal {
    void sound() {
        System.out.println("Animal makes a sound");
    }
}

class Dog extends Animal {
    @Override
    void sound() {
        System.out.println("Dog barks");
    }
}

public class Test {
    public static void main(String[] args) {
        Animal myAnimal = new Animal();
        myAnimal.sound();  // Output: Animal makes a sound

        Dog myDog = new Dog();
        myDog.sound();  // Output: Dog barks

        Animal animalRef = new Dog();
        animalRef.sound();  // Output: Dog barks (runtime polymorphism)
    }
}
  • Dog overrides the sound() method.
  • When calling sound() via an Animal reference pointing to a Dog object, the overridden method in Dog is invoked (dynamic dispatch).

@Override Annotation

  • Optional but recommended.
  • Helps the compiler check if you are actually overriding a method.
  • If method signatures don't match, compiler gives an error.

Overriding vs Overloading

Aspect Overriding Overloading
Happens between Superclass and subclass Same class
Method signature Must be same Different parameter list
Return type Same or covariant Can be different
Purpose Runtime polymorphism Compile-time polymorphism

Summary

Point Explanation
Overriding Subclass method replaces superclass method
Method signature Must be identical
Return type Same or subtype (covariant)
Access modifier Cannot be more restrictive
Exception handling Can throw fewer or narrower exceptions
Used for Runtime polymorphism and specific behavior

Super class, Abstract class, and Super Abstract Class


🔷 What is a Superclass?

  • A superclass (or parent class) is the class from which other classes (subclasses) inherit.
  • It provides common attributes and methods that subclasses can use or override.
  • For example:
class Animal {  // Superclass
    void eat() {
        System.out.println("This animal eats food.");
    }
}

class Dog extends Animal {  // Subclass
    void bark() {
        System.out.println("Dog barks.");
    }
}

Here, Animal is the superclass of Dog.


🔷 What is an Abstract Class?

  • An abstract class is a class that cannot be instantiated directly.
  • It can contain:

  • Abstract methods (methods without implementation) that subclasses must override.

  • Concrete methods (with implementation).
  • It’s used to define a common template for related classes.

Syntax:

abstract class Animal {
    abstract void sound();  // abstract method
    void sleep() {
        System.out.println("Animal sleeps");
    }
}
  • Any class extending Animal must provide implementation for sound().

🔷 What is a Super Abstract Class?

  • The term Super Abstract Class usually refers to an abstract class that acts as a superclass to other subclasses.
  • It's the top-level abstract class in an inheritance hierarchy providing shared abstract methods and sometimes concrete methods.
  • Other abstract or concrete subclasses extend it and provide specific implementations.

Example:

abstract class Vehicle {  // Super Abstract Class
    abstract void start();

    void stop() {
        System.out.println("Vehicle stopped.");
    }
}

class Car extends Vehicle {
    @Override
    void start() {
        System.out.println("Car started.");
    }
}

class Bike extends Vehicle {
    @Override
    void start() {
        System.out.println("Bike started.");
    }
}
  • Vehicle is a super abstract class — it cannot be instantiated, but defines a contract for subclasses.
  • Car and Bike provide their own implementations of the abstract start() method.

Summary:

Term Description
Superclass Parent class that other classes inherit from
Abstract class Class that can't be instantiated and may contain abstract methods
Super Abstract Class Abstract class serving as a top-level superclass for subclasses

Key Points about Abstract Classes:

  • Cannot create objects of abstract class.
  • Can have constructors (called when subclasses are created).
  • Can contain both abstract and concrete methods.
  • Helps in designing frameworks and enforcing method implementations.