Tools
Log in
English

Learn to codeJava

Java inheritance

Based on Java 17

Java inheritance with extends, super and @Override, using dogs and cats.

In one line

With extends, a class takes over its parent’s fields and methods as they are and overrides only the parts that differ.

Why you need it

Separate Dog and Cat classes would each carry a name, a meal count and an eat method. Change the eating rule and you must edit both; miss one and the animals start behaving differently.

Keep the shared part once in Animal and write only the real differences, such as the sound, in Dog and Cat. A Rabbit later needs only its own differences.

Everyday picture

Picture a shop chain’s operating manual. Each branch uses the head office manual as it is and swaps only local pages, such as the menu. When a shared rule like opening hours changes, only the head office manual is edited.

Example code

Main.java · 63 lines
class Animal {    protected final String name;    private int meals;     Animal(String name) {        this.name = name;    }     void eat() {        meals++;        System.out.println(name + " ate (" + meals + ")");    }     String sound() {        return "...";    }     String introduce() {        return name + " says " + sound();    }} class Dog extends Animal {    Dog(String name) {        super(name);    }     @Override    String sound() {        return "Woof";    }     void fetch() {        System.out.println(name + " brings the ball back");    }} class Cat extends Animal {    private final boolean indoor;     Cat(String name, boolean indoor) {        super(name);        this.indoor = indoor;    }     @Override    String sound() {        return indoor ? "Meow" : "Hiss";    }} public class Main {    public static void main(String[] args) {        Dog dog = new Dog("Bori");        Cat cat = new Cat("Nabi", true);        dog.eat();        cat.eat();        dog.eat();        System.out.println(dog.introduce());        System.out.println(cat.introduce());        dog.fetch();    }}

When to use it

  • The sentence "a dog is an animal" sounds right
  • Several classes share fields and behavior and differ in only a few spots
  • You want to handle many children through one parent type (next topic: polymorphism)

A Java class has exactly one parent. If "has a" fits better than "is a", put the other object in a field instead (composition).

Common mistakes

Forgetting super(...) in the child constructor

If the parent has no constructor without parameters, the child constructor must start with super(...). Otherwise Java inserts super() for you and fails.

Wrong

class Dog extends Animal {    Dog(String name) {        this.name = name;    }}

What javac sayserror: constructor Animal in class Animal cannot be applied to given types;

Fixed

class Dog extends Animal {    Dog(String name) {        super(name);    }}

A typo stops the override

Writing Sound instead of sound just adds another method, so there is no error and the parent’s "..." comes out. Mark it with @Override and javac catches the typo ("method does not override").

Wrong

class Dog extends Animal {    String Sound() {        return "Woof";    }} public class Main {    public static void main(String[] args) {        Animal a = new Dog();        System.out.println(a.sound());    }}

When you run it...

Fixed

class Dog extends Animal {    @Override    String sound() {        return "Woof";    }} public class Main {    public static void main(String[] args) {        Animal a = new Dog();        System.out.println(a.sound());    }}

When you run itWoof

Using the parent’s private field in the child

Private fields stay visible only inside the parent, even after inheritance. Change them through a parent method, or make them protected if children really need them.

Wrong

class Dog extends Animal {    void eatTwice() {        meals += 2;    }}

What javac sayserror: meals has private access in Animal

Fixed

class Dog extends Animal {    void eatTwice() {        eat();        eat();    }}

Check yourself

Question 1

A Cat is stored in an Animal variable. What does introduce() print?

public class Main {    public static void main(String[] args) {        Animal pet = new Cat("Coco", false);        System.out.println(pet.introduce());    }}

Show the answer

Answer: 3. Coco says Hiss The variable type is Animal, but the object is a Cat, so Cat.sound() runs. indoor is false, so it is "Hiss".

Question 2

What happens with class Puppy extends Dog, Animal { }?

Show the answer

Answer: 2. It does not compile A Java class names exactly one parent after extends. To take on several contracts, implements several interfaces instead.

Questions people ask

How is inheritance different from implementing an interface?

extends takes over fields and method bodies, and there is only one parent. implements takes on a set of method promises, and a class can take many.

Do I have to write @Override?

Code runs without it, but write it anyway. If the name or parameters are wrong, javac reports an error.

When do I use super?

On the first line of a child constructor to call the parent constructor (super(name)), and inside an overriding method to call the parent version (super.sound()).