Inheritance: extends

Reusing a class

Inheritance lets a new class get everything from an existing class, then add its own extras. The existing class is the parent (or superclass); the new one is the child (or subclass).

Think of it like this: Children inherit things from their parents – like eye colour – but also have their own talents. A Car and a Bike are both Vehicles: they share wheels and speed, but only a car has a boot.

class Animal {
    String name;

    void eat() {
        System.out.println(name + " is eating");
    }
}

class Dog extends Animal {
    void bark() {
        System.out.println(name + " says Woof!");
    }
}

public class Main {
    public static void main(String[] args) {
        Dog d = new Dog();
        d.name = "Bruno";
        d.eat();
        d.bark();
    }
}

Output

Bruno is eating
Bruno says Woof!

Dog never wrote name or eat() – it got them from Animal.

The “is a” test

Use inheritance only when the child really is a kind of the parent: a Dog is an Animal, a Manager is an Employee. A Car is not an Engine (a car has an engine), so that would be a field, not inheritance.

Remember: A Java class can extend only one parent class.

HOME LABS COMMUNITY DASHBOARD