Method overriding is when a subclass provides its own implementation of a method that is already defined in its parent class, with the same method name, parameters, and return type. It is used to achieve runtime polymorphism.
- The method must have the same name and parameters.
- The return type must be the same (or covariant).
- The method cannot be less accessible (e.g., public → private).
- The overriding method cannot throw broader checked exceptions.
- The method must not be static, private, or final.
- Overloading → Compile-time polymorphism, methods have the same name but different parameters.
- Overriding → Runtime polymorphism, methods have the same name and parameters but are defined in different classes (parent-child).
class Animal {
void sound() {
System.out.println("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
System.out.println("Dog barks");
}
}
public class TestOverride {
public static void main(String[] args) {
Animal a = new Dog(); // Upcasting
a.sound(); // Output: Dog barks
}
}
Static methods cannot be overridden, they can only be hidden
class Parent {
static void display() {
System.out.println("Static method in Parent");
}
}
class Child extends Parent {
static void display() {
System.out.println("Static method in Child");
}
}
public class TestStaticOverride {
public static void main(String[] args) {
Parent p = new Child();
p.display(); // Output: Static method in Parent
}
}