CodeBlanks Logo Icon CodeBlanks

Override rules

Learn @Override and its rules.

Override and @Override

When you override a method, adding the @Override annotation is a good habit. It tells the compiler "I intend to override this method." If the signature has a typo, you get a compile error; this catches silent bugs.

Do not confuse override with overload. Overload defines a new method with the same name but a different parameter list; it does not use dynamic dispatch. Override replaces the parent method.

Calling the parent with super

Sometimes you want to call the parent version of a method you overrode. super.method() does that. For instance super.area() runs the parent's area method; you can use its result inside the child method.

This is especially useful in the template method pattern: the parent provides an algorithm skeleton, and subclasses customize some steps while keeping the skeleton via super.

Practice Use override + super to build a sound

Define class Animal with a String sound() { return ""; } method. Define class Dog extends Animal that overrides sound with @Override and returns super.sound() + "Woof";. In main, assign with Animal a = new Dog(); and print System.out.println(a.sound());.

Starter code

Main.java
// Define the Animal class: sound returns the empty string

// Dog extends Animal; the sound method is overridden

// main: assign a Dog instance as Animal and print

Sample solution

Main.java
class Animal {
    String sound() { return ""; }
}

class Dog extends Animal {
    @Override
    String sound() { return super.sound() + "Woof"; }
}

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

Expected output

Woof

Questions and answers

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

1 Which of the following is NOT override?

  • A subclass method marked @Override with matching signature
  • Widening a protected parent method to public
  • A new method with the same name but different parameters Correct answer
  • Implementing an abstract method in a concrete subclass

Explanation: Same name with different parameters is overload, not override.

2 Add the override annotation

Question
class Dog extends Animal {
    ____
    String sound() { return "Woof"; }
}
Answer
class Dog extends Animal {
    @Override
    String sound() { return "Woof"; }
}

Explanation: @Override tells the compiler this method overrides the parent.

3 Match the override and overload concepts

Term Meaning
@Override Marks override intent
overload Same name, different parameters
super.method() Calls the parent method
final Blocks override

All lessons in Intermediate