← Back to Curriculum

Inheritance and Polymorphism

📚 Lesson 5 of 16 ⏱ 45 min

Inheritance and Polymorphism

45 min

Inheritance is a fundamental OOP concept that allows classes to inherit properties and methods from parent classes, promoting code reuse and creating class hierarchies. Java supports single inheritance (a class can extend only one parent class) using the `extends` keyword. Subclasses inherit all non-private members from parent classes and can add new members or override inherited methods. Understanding inheritance helps you design class hierarchies and avoid code duplication.

Polymorphism ("many forms") allows objects of different classes to be treated as instances of a common parent class. This enables you to write code that works with the parent type but executes subclass-specific behavior. Polymorphism is achieved through method overriding—subclasses provide their own implementations of inherited methods. At runtime, Java calls the appropriate method based on the actual object type. Understanding polymorphism enables flexible, extensible designs.

The `super` keyword provides access to parent class members. It's used to call parent class constructors (`super()`), access parent class methods (`super.method()`), and access parent class fields (`super.field`). `super()` must be the first statement in a constructor if used. Understanding `super` helps you work with inheritance hierarchies and properly initialize parent class members.

Method overriding allows subclasses to provide specific implementations of methods defined in parent classes. Overridden methods must have the same signature (name, parameters, return type) and can't be more restrictive in access. The `@Override` annotation helps catch errors (like typos) and documents intent. Overriding enables polymorphism—the same method call can produce different behavior based on the object type. Understanding method overriding enables polymorphic behavior.

Abstract classes and interfaces provide additional inheritance mechanisms. Abstract classes can't be instantiated and can contain abstract methods (methods without implementation). Interfaces define contracts that classes must implement. Java 8+ allows interfaces to have default and static methods. Classes can implement multiple interfaces but extend only one class. Understanding abstract classes and interfaces helps you design flexible, extensible systems.

Best practices include using inheritance for "is-a" relationships, favoring composition over inheritance when appropriate, using `@Override` annotation, calling `super()` in constructors when needed, and designing clear class hierarchies. Inheritance should represent logical relationships, not just code reuse. Understanding inheritance and polymorphism enables you to design flexible, maintainable object-oriented systems.

Key Concepts

  • Inheritance allows classes to inherit from parent classes using extends.
  • Polymorphism allows treating objects as parent class instances.
  • super keyword accesses parent class members.
  • Method overriding provides subclass-specific implementations.
  • Abstract classes and interfaces provide additional inheritance mechanisms.

Learning Objectives

Master

  • Creating class hierarchies with inheritance
  • Understanding polymorphism and method overriding
  • Using super keyword to access parent class members
  • Working with abstract classes and interfaces

Develop

  • Object-oriented design thinking
  • Understanding inheritance relationships and hierarchies
  • Designing flexible, extensible class structures

Tips

  • Use inheritance for 'is-a' relationships, not just code reuse.
  • Use @Override annotation to catch errors and document intent.
  • Call super() in constructors when parent class has a constructor.
  • Favor composition over inheritance when appropriate.

Common Pitfalls

  • Creating deep inheritance hierarchies that are hard to maintain.
  • Not calling super() in constructors when parent has a constructor.
  • Overriding methods incorrectly, causing compilation errors.
  • Using inheritance when composition would be more appropriate.

Summary

  • Inheritance enables code reuse and class hierarchies.
  • Polymorphism allows flexible, extensible designs.
  • super keyword accesses parent class members.
  • Method overriding enables polymorphic behavior.
  • Understanding inheritance and polymorphism is essential for OOP.

Exercise

Create a hierarchy of animals with inheritance and demonstrate polymorphism.

// Animal class (parent)
class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void makeSound() {
        System.out.println("Some animal sound");
    }
}

// Dog class (child)
class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + " says: Woof!");
    }
}

// Cat class (child)
class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    
    @Override
    public void makeSound() {
        System.out.println(name + " says: Meow!");
    }
}

public class InheritanceDemo {
    public static void main(String[] args) {
        Animal[] animals = {
            new Dog("Buddy"),
            new Cat("Whiskers"),
            new Animal("Generic Animal")
        };
        
        for (Animal animal : animals) {
            animal.makeSound(); // Polymorphism in action
        }
    }
}

Code Editor

Output