Course contentsShow
← Java
Lesson 438 of 2,87010. Inheritance FundamentalsFree lesson

Real-World is-a Examples: Building Class Hierarchies

Apply is-a reasoning to design meaningful inheritance hierarchies like Animal, Vehicle, Shape.

Real-World is-a Examples: Building Class Hierarchies

What you'll learn: How to apply is-a reasoning to design meaningful, real-world inheritance hierarchies.

Understanding Class Hierarchy Design

Now that you know inheritance theory, let's see how professional developers build class hierarchies using is-a relationships. The key is starting with a general concept and extending it with more specific types.

Animal Hierarchy

class Animal {
    protected String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public void eat() {
        System.out.println(name + " is eating");
    }
}

class Dog extends Animal {
    public Dog(String name) {
        super(name);
    }
    
    public void bark() {
        System.out.println(name + " barks!");
    }
}

class Cat extends Animal {
    public Cat(String name) {
        super(name);
    }
    
    public void meow() {
        System.out.println(name + " meows!");
    }
}

Why it works: A Dog is-a Animal. A Cat is-a Animal. Both share eating behavior but have unique behaviors.

Vehicle Hierarchy

class Vehicle {
    protected int speed;
    
    public void accelerate() {
        speed += 10;
    }
}

class Car extends Vehicle {
    private int doors;
    // Car-specific features
}

class Motorcycle extends Vehicle {
    private boolean hasSidecar;
    // Motorcycle-specific features
}

Shape Hierarchy

class Shape {
    public double getArea() {
        return 0.0;
    }
}

class Circle extends Shape {
    private double radius;
    
    @Override
    public double getArea() {
        return Math.PI * radius * radius;
    }
}

class Rectangle extends Shape {
    private double width, height;
    
    @Override
    public double getArea() {
        return width * height;
    }
}

The pattern: Start with shared characteristics in the superclass, then specialize with subclasses that add unique fields and methods.

Key Takeaway: Real-world hierarchies model general-to-specific relationships where subclasses are specialized versions of their parent, inheriting common behavior while adding their own unique features.