Java
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.
Exercise 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.
Show example solution
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();
}
}
Test yourself
-
Which is true about overriding?
- The method signature must match
- The method signature must differ
- The method name must change
- The parameter count must increase
Show answer
The method signature must match — In overriding, the method signature must match.
-
Add the @Override annotation
class Cat extends Animal {
____
void sound() {
System.out.println("Miyav");
}
}
Show answer
class Cat extends Animal {
@Override
void sound() {
System.out.println("Miyav");
}
}
-
Match the override parts
- @Override
- Annotation
- sound
- Method name
- Meow
- New output
- Cat extends Animal
- Inheritance link
Next lesson: Object class