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

Practical Example: Animal and Dog Hierarchy

Walk through a concrete example defining Animal as a superclass and Dog as a subclass to solidify inheritance basics.

Practical Example: Animal and Dog Hierarchy

You'll learn: How to apply inheritance basics by building a simple Animal superclass and Dog subclass that demonstrates field and method inheritance in action.

The Scenario

Let's create a hierarchy where Animal defines common characteristics (like name and makeSound()), and Dog inherits these while adding dog-specific behavior (like fetch()).

The Animal Superclass

public class Animal {
    private String name;
    
    public Animal(String name) {
        this.name = name;
    }
    
    public String getName() {
        return name;
    }
    
    public void makeSound() {
        System.out.println(name + " makes a sound");
    }
}

The Dog Subclass

public class Dog extends Animal {
    public Dog(String name) {
        super(name);  // Call Animal's constructor
    }
    
    public void fetch() {
        System.out.println(getName() + " fetches the ball!");
    }
}

Notice Dog doesn't declare a name field—it inherits it from Animal. The Dog constructor calls super(name) to initialize the inherited field properly.

Using the Hierarchy

Dog myDog = new Dog("Buddy");
myDog.makeSound();  // Inherited method: "Buddy makes a sound"
myDog.fetch();      // Dog-specific method: "Buddy fetches the ball!"

Animal genericAnimal = new Animal("Unknown");
genericAnimal.makeSound();  // Works fine
// genericAnimal.fetch();   // ERROR: Animal doesn't have fetch()

Why This Matters

Every Dog is-an Animal, so it automatically gets Animal's capabilities. You avoid duplicating the name field and makeSound() method in every animal type you create. Dog focuses only on what makes it unique.

Key Takeaway:
Inheritance lets subclasses reuse superclass fields and methods—Dog gains name and makeSound() from Animal without rewriting them, while adding its own fetch() behavior.