Method overriding is an OOP feature that allows a subclass to provide its own implementation of a method that is already defined in its parent class. It enables runtime polymorphism by allowing the method behavior to vary based on the actual object type.
Key Points: • Method overriding occurs when a child class defines a method with the same name, parameters, and return type as the parent class. • It allows subclasses to customize or extend the behavior of inherited methods. • The @Override annotation is commonly used to indicate an overridden method. • Method overriding is the foundation of runtime polymorphism in Java. • Static, final, and private methods cannot be overridden.
Example: A Vehicle class may define a start() method. Different subclasses such as Car and Bike can override this method to provide their own specific implementation.
Code Example:
class Vehicle {
void start() {
System.out.println("Vehicle Started");
}
}
class Car extends Vehicle {
@Override
void start() {
System.out.println("Car Started");
}
}
public class Main {
public static void main(String[] args) {
Vehicle vehicle = new Car();
vehicle.start();
}
}Interview Tip: A concise interview answer is:
"Method overriding is the process in which a subclass provides its own implementation of a method already defined in the parent class. It is used to achieve runtime polymorphism and allows child classes to define specific behavior."