0/30 Days Completed 0 Learning Days
Day 25 of 30 · Week 4 — OOPs Through Java
Method overriding: deeper practice
1 Learn
Overriding rules: same name, same parameters, compatible return type, and access that is not more restrictive than the parent's.
The @Override annotation asks the compiler to check you really are overriding. It catches typos.
private, static and final methods are not overridden.
2 See the Code
Java
class Employee {
double pay() { return 20000; }
}
class Manager extends Employee {
@Override
double pay() { return super.pay() + 15000; }
}
class Intern extends Employee {
@Override
double pay() { return 8000; }
}
public class Payroll {
public static void main(String[] args) {
Employee[] staff = { new Employee(), new Manager(), new Intern() };
for (Employee e : staff) {
System.out.println(e.pay());
}
}
}- Each subclass overrides pay() with its own rule.
- One loop calls pay() and each object answers in its own way — this is runtime polymorphism.
Output
20000.0 35000.0 8000.0
3 Practice
- Create Animal.sound() and override it in Cow and Cat. Store them in an Animal[] and loop.
Try it in your own Java setup or write it in the Practice Notebook.
4 Quick Check
1. What does @Override do?
2. Can a final method be overridden?
Step 5
Answer and check the Quick Check above to unlock this.