Inheritance: The Family Tree

Inheritance: The Family Tree in Java: Inheritance allows one class to inherit the attributes and methods of another.

Concept Explanation

Inheritance allows one class to inherit the attributes and methods of another.

  • Superclass (Parent): The class being inherited from.
  • Subclass (Child): The class that inherits.

Think of it like a Family Tree. A "Parent" has traits (like eye color). The "Child" inherits those traits but can also have their own unique traits (like a specific talent).


Syntax or Core Structure

class Vehicle {
    protected String brand = "Ford";
    public void honk() {
        System.out.println("Tuut, tuut!");
    }
}

// Car inherits from Vehicle
class Car extends Vehicle {
    private String modelName = "Mustang";
}

The 'super' Keyword

If you want to call a method or a constructor from the parent class, use super.

public Car() {
    super(); // Calls the Vehicle constructor
}

Common Mistakes

  1. Multiple Inheritance: Java does NOT allow a class to inherit from two parents (class Car extends Vehicle, Machine is illegal). You must use Interfaces for that.
  2. Private variables: Subclasses can't see private variables of the parent. Use protected if you want the child to have access.

Practice Exercises

  1. The Employee System: Create a parent class Employee (Name, ID) and a subclass Developer (ProgrammingLanguage).
  2. The Shape Family: Create a Shape class with a color attribute. Create a Circle subclass with a radius.
  3. Method Overriding: Research @Override. Create a parent method makeSound() and override it in a child class to produce a specific sound.