Method Overriding means redefining a parent class method in the child class with the same name, return type and parameters. Used to implement runtime polymorphism and customize behavior.
Example
class Animal {
void makeSound() {
System.out.println("Default sound");
}
}
class Dog extends Animal {
@Override
void makeSound() {
System.out.println("Bark");
}
}
Rules
Rule | isRequired |
---|---|
Same method name | β |
Same parameter list | β |
Same or covariant return type | β |
Must be inherited | β |
Use @Override annotation | β (recommended) |
Access modifier canβt be more restrictive | β |
- Only instance methods can be overridden - not static methods.
- Private methods are not inherited, so canβt be overridden.
- Constructors canβt be overridden.
Comparison
Overriding vs Overloading
Feature | Overloading | Overriding |
---|---|---|
Occurs In | Same class | Subclass (inheritance) |
Params | Must be different | Must be same |
Return Type | Can differ | Must be same (or covariant) |
Polymorphism Type | Compile-time | Runtime |
Tip
Think βcustom behavior in subclassesβ when you hear overriding.
Use @Override to catch mistakes early - itβs not required, but highly recommended.
Parent: _OOP Concepts