Script Valley
Java: Complete Language Course
Object-Oriented Programming in JavaLesson 2.3

Java inheritance and the extends keyword

extends keyword, superclass, subclass, method inheritance, constructor chaining with super, method overriding, @Override annotation, is-a relationship

Inheritance

Inheritance lets a subclass reuse fields and methods from a superclass, then extend or override behavior. Use it only when a genuine is-a relationship exists — a Dog is-an Animal, but a Car is-not-a Engine.

Superclass

public class Animal {
    protected String name;

    public Animal(String name) {
        this.name = name;
    }

    public String speak() {
        return name + " makes a sound";
    }
}

Subclass with Override

public class Dog extends Animal {
    private String breed;

    public Dog(String name, String breed) {
        super(name); // calls Animal's constructor
        this.breed = breed;
    }

    @Override
    public String speak() {
        return name + " barks!";
    }

    public String getBreed() { return breed; }
}
Dog d = new Dog("Rex", "Labrador");
System.out.println(d.speak());    // Rex barks!
System.out.println(d.getBreed()); // Labrador

super(name) must be the first statement in the subclass constructor when the superclass lacks a zero-argument constructor. Forgetting it is a compile error.

The @Override annotation is not required but makes the compiler verify you are actually overriding a parent method. Without it, a typo silently creates a new method instead of overriding, and callers get the parent's behavior.

Java supports single class inheritance only. Use interfaces when multiple-type contracts are needed.

Favor composition over inheritance when the relationship is has-a rather than is-a. Inheritance couples subclass to superclass tightly — changes in the superclass ripple down. Composition (holding an object reference as a field) is more flexible and easier to test.

Up next

Java polymorphism and method overriding at runtime

Sign in to track progress