Method overriding is a feature of Java where a subclass provides its own implementation of a method that is already defined in its parent class. The overridden method must have the same name, parameter list, and compatible return type as the method in the superclass. Method overriding enables runtime polymorphism, allowing Java to execute the appropriate method based on the actual object type.
Key Points: • Method overriding occurs between a parent class and a child class. • The method name and parameter list must be exactly the same. • The return type must be the same or covariant (a subclass type). • The access level of the overridden method cannot be more restrictive. • Overriding enables runtime polymorphism (dynamic method dispatch).
Example: A Vehicle class may define a start() method, but different vehicle types can provide their own implementation of how they start.
Code Example:
class Vehicle {
void start() {
System.out.println("Vehicle is starting");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car is starting with a key");
}
}
public class Demo {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start();
}
}Output:
Car is starting with a key
Rules for Method Overriding:
• Method name must be the same. • Parameter list must be identical. • Return type must be the same or covariant. • Access modifier cannot be more restrictive than the parent method. • Final methods cannot be overridden. • Static methods are hidden, not overridden. • Private methods cannot be overridden because they are not inherited.
Example of Invalid Overriding:
class Parent {
public void display() {
}
}
class Child extends Parent {
private void display() { // Compilation Error
}
}The child method has weaker access privileges, which is not allowed.
Benefits of Method Overriding:
• Supports runtime polymorphism • Allows customization of inherited behavior • Improves flexibility and extensibility • Promotes code reuse through inheritance
Interview Tip: A concise interview answer is:
"Method overriding occurs when a subclass provides its own implementation of a method already defined in the parent class. The method must have the same name, parameters, and compatible return type. It is the foundation of runtime polymorphism in Java."