Method overriding and its rules
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)A parent class has a calculateFee() method, but a premium child needs a different calculation. You want to change it without touching the parent.
Writing your own version
Method overriding is when a child class gives its own body to an instance method it inherited, keeping the same name and parameter list. A call on a child object then runs the child's version instead of the parent's.
Every employee gets a 10% bonus, but a manager gets 20%. A new method like managerBonus() would make every caller remember which method fits which object. Overriding keeps one name, bonus(), for everyone.
Example 1 · A manager overrides bonus()
class Employee { String name;
Employee(String name) { this.name = name; }
int bonus(int salary) { return salary * 10 / 100; }}
class Manager extends Employee { Manager(String name) { super(name); }
int bonus(int salary) { return salary * 20 / 100; }}
public class BonusDemo { public static void main(String[] args) { Employee e = new Employee("Rohan"); Manager m = new Manager("Priya"); System.out.println(e.name + " bonus: Rs. " + e.bonus(50000)); System.out.println(m.name + " bonus: Rs. " + m.bonus(50000)); }}Rohan bonus: Rs. 5000 Priya bonus: Rs. 10000
What this code does
Managerhas abonus(int salary)with the same name, parameter and return type, so it overrides the parent version.- The
Employeeobject still uses the parent version.nameis inherited, andManager's constructor passes it up withsuper(name).
The parent version is not deleted: Employee objects still use it, and so does any child that does not override it. Overriding is what makes runtime polymorphism (opens in a new tab) work.
The rules of overriding
Overriding rules: the child method must have the same name and parameter types, a return type that is the same (or a subtype for class types) and access that is the same or wider. Private, static and final methods cannot be overridden.
Java treats a child method as an override only when it matches closely. The method signature, the name plus the parameter types in order, must be the same. Parameter names do not count.
Example 2 · Mistake: a different return type
class Shape { double area() { return 0; }}
class Square extends Shape { int side = 4;
int area() { return side * side; }}
public class ReturnTypeDemo { public static void main(String[] args) { System.out.println(new Square().area()); }}ReturnTypeDemo.java:10: error: area() in Square cannot override area() in Shape
int area() {
^
return type int is not compatible with double
1 errorWhat this code does
- Same name and parameters, so Java sees an attempt to override. But
intis notdouble, and primitive return types must match exactly. - The fix is
double area()inSquaretoo. Theintresult 16 is then returned as16.0.
Example 3 · Trap: different parameters only overload
class Fee { int amount(int months) { return months * 1000; }}
class HostelFee extends Fee { int amount(double months) { return (int) (months * 1500); }}
public class OverloadTrap { public static void main(String[] args) { HostelFee h = new HostelFee(); System.out.println("Hostel fee: Rs. " + h.amount(2)); }}Hostel fee: Rs. 2000
What this code does
amount(double)has a different parameter type, so it does not overrideamount(int).HostelFeenow has both methods.- The argument
2is anint, so the inheritedamount(int)is the exact match and the parent rate of Rs. 1000 a month is used. - It compiles and runs, which makes this mistake hard to spot. Changing the child to
int amount(int months)fixes it: Rs. 3000.
Different parameters are not an error at all: the child method becomes an overload, a second method next to the inherited one. Nothing is replaced, and the program quietly runs the parent version. The next lesson shows how @Override catches this.
Covariant return type
Covariant return type means an overriding method may return a subtype of the parent method's return type, for example TatkalTicket instead of Ticket. It works only for class types; primitive return types must match exactly.
Ticket has copyFor(route), which returns a Ticket for a new route. A Tatkal ticket's copy is also a Tatkal ticket, so its override may promise more: it returns a TatkalTicket.
Example 4 · A covariant return type
class Ticket { String route;
Ticket(String route) { this.route = route; }
Ticket copyFor(String newRoute) { return new Ticket(newRoute); }}
class TatkalTicket extends Ticket { TatkalTicket(String route) { super(route); }
TatkalTicket copyFor(String newRoute) { return new TatkalTicket(newRoute); }
int tatkalFee() { return 200; }}
public class CovariantDemo { public static void main(String[] args) { TatkalTicket t = new TatkalTicket("Delhi-Agra"); TatkalTicket back = t.copyFor("Agra-Delhi"); System.out.println(back.route + ", Tatkal fee Rs. " + back.tatkalFee()); }}Agra-Delhi, Tatkal fee Rs. 200
What this code does
- The override returns
TatkalTicket, a subtype of the parent'sTicket. That is a covariant return type, and it is still an override. - Because
copyForon aTatkalTicketpromises aTatkalTicket, the caller can store it in aTatkalTicketvariable and calltatkalFee()directly.
This is safe: a TatkalTicket is a Ticket, so any caller that expects a Ticket still gets one. Going the other way, a child returning a more general type, is an error.
Access cannot be weaker
Code that can call pay() on any Payment expects to call it on every kind of payment. So an override may keep the access or open it wider, never close it.
Example 5 · Mistake: weaker access
class Payment { public void pay(int amount) { System.out.println("Paying Rs. " + amount); }}
class UpiPayment extends Payment { void pay(int amount) { System.out.println("UPI: Rs. " + amount); }}
public class AccessDemo { public static void main(String[] args) { new UpiPayment().pay(100); }}AccessDemo.java:8: error: pay(int) in UpiPayment cannot override pay(int) in Payment
void pay(int amount) {
^
attempting to assign weaker access privileges; was public
1 errorWhat this code does
- The parent
payispublic; the child version has no keyword, which is default access, narrower thanpublic. - The message says it directly: "weaker access privileges; was public". Write
public void pay(int amount)in the child.
From closed to open: private → default (no keyword) → protected → public. A public parent method needs a public override; a protected one allows protected or public.
The same promise covers exceptions: an override cannot throw a new or broader checked exception than the parent method declares, because callers are not ready to catch it. Unchecked exceptions are always allowed.
Methods you cannot override
Three kinds of methods cannot be overridden: final methods are locked, as in final methods (opens in a new tab); private methods are not inherited; static methods belong to the class, not to an object.
Example 6 · Surprise: a private method is not overridden
class Account { private void fee() { System.out.println("Account fee: Rs. 100"); }
void monthEnd() { fee(); }}
class StudentAccount extends Account { void fee() { System.out.println("Student fee: Rs. 0"); }}
public class PrivateDemo { public static void main(String[] args) { StudentAccount s = new StudentAccount(); s.monthEnd(); s.fee(); }}Account fee: Rs. 100 Student fee: Rs. 0
What this code does
fee()inAccountisprivate, soStudentAccountdoes not inherit it. Itsfee()is a new, separate method.monthEnd()lives inAccountand callsAccount's own privatefee(), so the student is still charged Rs. 100 at month end.
A static method with the same signature in the child hides the parent one instead of overriding it; Field hiding vs method overriding (opens in a new tab) shows the difference. Constructors are not inherited, so they cannot be overridden either.
Fix the error
Fix the broken override
Read the error, then pick the line that fixes it.
Round 1 of 5
Payment has public void pay(int amount). UpiPayment should replace it.
Error
UpiPayment.java:2: error: pay(int) in UpiPayment cannot override pay(int) in Payment attempting to assign weaker access privileges; was public
Next step
Check your understanding
12 quick questions