Method Overriding
Method overriding allows a child class to provide its own version of a method that is already defined in the parent class. This is one of the most important concepts that makes Java truly object-oriented.
In real applications, method overriding is used whenever different objects need to respond differently to the same action.
Real-World Example of Method Overriding
Think about an employee management system. All employees receive salaries, but the calculation differs:
- A full-time employee has a fixed salary
- A contract employee is paid hourly
The action is the same — calculate salary. The implementation is different. That is method overriding.
Basic Rule of Method Overriding
For a method to be overridden in Java:
- The method name must be the same
- The method parameters must be the same
- The method must be inherited
- The child class provides a new implementation
Simple Method Overriding Example
First, let’s define a parent class.
class Employee {
void calculateSalary() {
System.out.println("Calculating employee salary");
}
}
Now we override the method in child classes.
class FullTimeEmployee extends Employee {
void calculateSalary() {
System.out.println("Salary is fixed per month");
}
}
class ContractEmployee extends Employee {
void calculateSalary() {
System.out.println("Salary is calculated per hour");
}
}
Method Overriding in Action
Now let’s see how Java decides which method to execute.
public class Main {
public static void main(String[] args) {
Employee emp1 = new FullTimeEmployee();
Employee emp2 = new ContractEmployee();
emp1.calculateSalary();
emp2.calculateSalary();
}
}
Output:
Salary is fixed per month
Salary is calculated per hour
Even though both references are of type Employee,
Java executes the correct method based on the actual object.
Why Method Overriding Is Powerful
Method overriding helps developers:
- Write flexible and reusable code
- Extend behavior without changing existing classes
- Implement runtime polymorphism
- Design scalable systems
This concept is heavily used in frameworks, APIs, and large enterprise systems.
Common Mistakes to Avoid
- Changing method parameters while overriding
- Using different method names
- Reducing access level of overridden methods
Java provides the @Override annotation to help avoid these mistakes.
Using @Override Annotation
The @Override annotation tells the compiler that a method is meant
to override a parent method.
If it does not, Java will throw an error.
class Manager extends Employee {
@Override
void calculateSalary() {
System.out.println("Manager salary includes bonuses");
}
}
Key Takeaways
- Method overriding allows child classes to change behavior
- It supports runtime polymorphism
- Same method signature, different implementation
- Widely used in real-world Java applications
In the next lesson, we will build on this concept and explore abstraction, which takes object-oriented design to the next level.