Careeroza
Method Overriding
Rules
Overriding means a subclass provides its own version of a method it inherited. The method is chosen at runtime based on the actual object.
| Rule | Detail |
|---|---|
| Same signature | same name and same parameter types |
| Return type | same, or a subtype (covariant return) |
| Access | same or wider (protected → public is ok, public → private is not) |
| Exceptions | cannot throw new or broader checked exceptions |
| Cannot override | final, static and private methods |
Overriding with @Override
Example
Each notification type sends in its own way. @Override asks the compiler to check that you really override a parent method.
public class Main {
public static void main(String[] args) {
Notification[] list = { new Notification(), new SmsNotification(), new EmailNotification() };
for (Notification n : list) {
n.send("Your order is out for delivery");
}
}
}
class Notification {
void send(String msg) {
System.out.println("[generic] " + msg);
}
}
class SmsNotification extends Notification {
@Override
void send(String msg) {
System.out.println("[SMS] " + msg.substring(0, 14) + "...");
}
}
class EmailNotification extends Notification {
@Override
void send(String msg) {
System.out.println("[Email] Subject: Update | Body: " + msg);
}
}Output
[generic] Your order is out for delivery [SMS] Your order is ... [Email] Subject: Update | Body: Your order is out for delivery
Why @Override Matters
A typo creates a new method instead of overriding. With @Override the compiler catches it.
class Animal {
void makeSound() { }
}
class Dog extends Animal {
@Override
void makesound() { } // error: method does not override or implement a method from a supertype
}Tip: Always write @Override. It costs nothing and prevents silent bugs.