CodeBlanks Logo Icon CodeBlanks

Method overriding

Learn to override methods in derived classes.

Method overriding

A subclass can redefine a method from its superclass; this is called overriding. The method signature must match: same name, same parameter list. The @Override annotation is used to state this explicitly.

Example: class Animal { void sound() { System.out.println("Sound"); } } class Cat extends Animal { @Override void sound() { System.out.println("Meow"); } }. Here Cat overrides sound. When sound() is called on a Cat instance, it prints "Meow". The @Override annotation causes a compile error if the signature is wrong; it provides safety.

Why use @Override?

The @Override annotation tells the compiler that this method overrides one from the superclass. If you write the wrong signature, you get a compile error. This prevents silent mistakes; even a typo is caught at compile time.

Example: If you accidentally write soudn() instead of sound(), without @Override this becomes a new method and the superclass's method silently stays. With @Override, the compiler cannot find soudn in Animal and reports an error. That is why always using @Override is a good habit when overriding.

Practice Override the sound method in Cat

Define a class Animal with a void sound() method whose body writes System.out.println("Sound");. Define Cat extends Animal; override sound with @Override, writing System.out.println("Meow"); in the body. Put main inside Cat; create a Cat instance and call the sound method.

Starter code

Main.java
// Define the Animal class
// Override the sound method in Cat
// Instantiate and call in main

Sample solution

Main.java
class Animal {
    void sound() {
        System.out.println("Sound");
    }
}
class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Meow");
    }
    public static void main(String[] args) {
        Cat c = new Cat();
        c.sound();
    }
}

Expected output

Meow

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which is true about overriding?

  • The method signature must match Correct answer
  • The method signature must differ
  • The method name must change
  • The parameter count must increase

Explanation: In overriding, the method signature must match.

2 Add the @Override annotation

Question
class Cat extends Animal {
    ____
    void sound() {
        System.out.println("Miyav");
    }
}
Answer
class Cat extends Animal {
    @Override
    void sound() {
        System.out.println("Miyav");
    }
}

Explanation: The @Override annotation marks the override.

3 Match the override parts

Term Meaning
@Override Annotation
sound Method name
Meow New output
Cat extends Animal Inheritance link

All lessons in Intermediate