Introduction & Syntax
Polymorphism and Method Overriding · Study material
Polymorphism – "many forms" – means one piece of code can work with objects of many different types, each responding in its own way. In Java it comes in two flavours. Compile-time polymorphism is method overloading: several methods with the same name and different parameters, chosen by the compiler. Run-time polymorphism is method overriding: a subclass redefines a method it inherits, and the JVM decides at run time which version to call based on the actual object (dynamic method dispatch). That is what lets a single checkout(Payment p) handle UPI, card and net-banking payments, and lets you add a new payment type without touching existing code. This page explains both kinds, all the rules for overriding (signatures, covariant return types, access, exceptions, and why static, private and final methods are different), and the modern pattern-matching alternative. Then practise with 60 questions – 20 MCQs, 20 predict-the-output puzzles, 10 find-the-error programs and 10 complete programs – compiled and run on Java 21.
On this page
- Run-time polymorphism and dynamic method dispatch
- Compile-time polymorphism: overloading and how a method is chosen
- Rules for overriding, with @Override
- What is not polymorphic: fields, static and private methods
- Calling the parent version with super
- Overloading vs overriding; sealed types and pattern-matching switch
Run-time polymorphism
A superclass (or interface) variable can refer to any subclass object. When you call an overridden method through it, the JVM looks at the actual object, not the variable's type, and runs that class's version. The compiler only checks that the method exists in the declared type.
import java.util.List;
class Payment {
protected final double amount;
Payment(double amount) { this.amount = amount; }
double fee() { return 0; }
String method() { return "generic"; }
}
class UpiPayment extends Payment {
UpiPayment(double a) { super(a); }
@Override double fee() { return 0; } // UPI: free
@Override String method() { return "UPI"; }
}
class CardPayment extends Payment {
CardPayment(double a) { super(a); }
@Override double fee() { return amount * 0.02; } // 2%
@Override String method() { return "Card"; }
}
class NetBanking extends Payment {
NetBanking(double a) { super(a); }
@Override double fee() { return 15; } // flat Rs 15
@Override String method() { return "NetBanking"; }
}
public class Main {
// ONE method works for every kind of payment – including kinds added in future
static void checkout(Payment p) {
System.out.printf("%-10s amount %8.2f fee %6.2f total %8.2f%n", p.method(), p.amount, p.fee(), p.amount + p.fee());
}
public static void main(String[] args) {
List<Payment> payments = List.of(new UpiPayment(1500), new CardPayment(1500), new NetBanking(1500));
for (Payment p : payments) checkout(p); // the JVM picks each object's own fee() and method()
}
}
UPI amount 1500.00 fee 0.00 total 1500.00 Card amount 1500.00 fee 30.00 total 1530.00 NetBanking amount 1500.00 fee 15.00 total 1515.00
Compile-time polymorphism (overloading)
Overloaded methods share a name but differ in the number, types or order of parameters (the return type alone is not enough). The compiler picks one using the declared argument types, in three phases: exact match or widening first, then boxing/unboxing, then varargs.
public class Main {
// Overloading: same name, different parameter lists – chosen by the COMPILER from the argument types
static double area(double r) { return Math.PI * r * r; } // circle
static double area(double w, double h) { return w * h; } // rectangle
static double area(double a, double b, double c) { // triangle (Heron)
double s = (a + b + c) / 2;
return Math.sqrt(s * (s - a) * (s - b) * (s - c));
}
static String describe(int x) { return "int"; }
static String describe(long x) { return "long"; }
static String describe(Integer x) { return "Integer"; }
static String describe(Object x) { return "Object"; }
static String describe(int... xs) { return "varargs"; }
public static void main(String[] args) {
System.out.printf("%.2f %.1f %.1f%n", area(1), area(3, 4), area(3, 4, 5));
short s = 3;
System.out.println(describe(5) + " " + describe(s) + " " + describe(5L) + " " + describe(Integer.valueOf(5)) + " " + describe("hi") + " " + describe() + " " + describe(1, 2));
}
}
3.14 12.0 6.0 int int long Integer Object varargs varargs
Rules for overriding
| Rule | Detail |
|---|---|
| Same signature | same name and parameter types (otherwise it is an overload) |
| Return type | same, or a subtype for reference types (covariant return); primitives must match exactly |
| Access | same or wider – never narrower |
| Checked exceptions | same, narrower, fewer or none – never new or broader ones (unchecked exceptions are free) |
| Cannot override | final methods, static methods (they are hidden), private methods (not inherited), constructors |
| @Override | optional but strongly recommended: the compiler then reports any mistake |
import java.io.FileNotFoundException;
import java.io.IOException;
class Document {
protected Document copy() { return new Document(); }
void save() throws IOException { System.out.println("Document saved"); }
public String title() { return "untitled"; }
}
class Invoice extends Document {
@Override
public Invoice copy() { return new Invoice(); } // ✔ covariant return type (subtype) and wider access
@Override
void save() throws FileNotFoundException { // ✔ narrower checked exception (or none at all)
System.out.println("Invoice saved");
}
@Override
public String title() { return "INV-001"; } // ✔ same signature, same return type
}
public class Main {
public static void main(String[] args) throws IOException {
Document d = new Invoice();
Document c = d.copy(); // runs Invoice.copy()
System.out.println(c.getClass().getSimpleName() + " " + d.title());
d.save();
Invoice inv = new Invoice().copy(); // no cast needed thanks to the covariant return
System.out.println(inv.title());
}
}
Invoice INV-001 Invoice saved INV-001
What is not polymorphic
Only instance methods are dispatched dynamically. Fields and static methods are chosen by the declared type, and a private method cannot be overridden at all – a same-named method in the subclass is unrelated.
class Parent {
String name = "Parent field"; // fields: chosen by the reference type
static String kind() { return "Parent static"; } // static methods: hidden, chosen by the reference type
String who() { return "Parent instance"; } // instance methods: overridden, chosen by the object
private String secret() { return "Parent private"; } // private: not inherited, so not overridden
String reveal() { return secret(); }
}
class Child extends Parent {
String name = "Child field";
static String kind() { return "Child static"; }
@Override String who() { return "Child instance"; }
String secret() { return "Child private?"; } // a brand-new method, not an override
}
public class Main {
public static void main(String[] args) {
Parent p = new Child();
System.out.println(p.name);
System.out.println(Parent.kind() + " / " + Child.kind());
System.out.println(p.who());
System.out.println(p.reveal());
}
}
Parent field Parent static / Child static Child instance Parent private
Overriding with super
An override can still call the version it replaces with super.method() – the usual way to extend rather than replace behaviour.
class Notifier {
String send(String msg) { return "[" + msg + "]"; }
}
class TimestampNotifier extends Notifier {
@Override String send(String msg) { return "09:30 " + super.send(msg); } // extend the parent behaviour
}
class UrgentNotifier extends TimestampNotifier {
@Override String send(String msg) { return super.send(msg.toUpperCase()) + " !!!"; }
}
public class Main {
public static void main(String[] args) {
Notifier[] all = {new Notifier(), new TimestampNotifier(), new UrgentNotifier()};
for (Notifier n : all) System.out.println(n.send("server down"));
}
}
[server down] 09:30 [server down] 09:30 [SERVER DOWN] !!!
Overloading vs overriding
| Overloading | Overriding | |
|---|---|---|
| Where | same class (or inherited) | subclass redefines a superclass method |
| Parameters | must differ | must be the same |
| Return type | can be anything | same or covariant |
| Chosen | at compile time, by declared argument types | at run time, by the actual object |
| Static methods | can be overloaded | cannot be overridden (only hidden) |
Sealed types and pattern-matching switch
Java 21 offers a second style. With a sealed hierarchy, a switch over the type is checked for exhaustiveness, so adding a new subtype produces compile errors everywhere it must be handled. Overriding is best when new types are added often; a pattern switch is best when new operations are added often.
// Java 21: a sealed hierarchy + pattern-matching switch is an alternative to overriding
// when the OPERATIONS change more often than the TYPES.
sealed interface Shape permits Circle, Rect, Tri { }
record Circle(double r) implements Shape { }
record Rect(double w, double h) implements Shape { }
record Tri(double b, double h) implements Shape { }
public class Main {
static double area(Shape s) {
return switch (s) { // exhaustive: the compiler knows every permitted subtype
case Circle c -> Math.PI * c.r() * c.r();
case Rect r -> r.w() * r.h();
case Tri t -> 0.5 * t.b() * t.h();
};
}
static String describe(Shape s) {
return switch (s) {
case Circle c when c.r() > 10 -> "large circle";
case Circle c -> "circle";
case Rect r when r.w() == r.h() -> "square";
case Rect r -> "rectangle";
case Tri t -> "triangle";
};
}
public static void main(String[] args) {
Shape[] shapes = {new Circle(1), new Rect(3, 3), new Tri(6, 4), new Circle(12)};
for (Shape s : shapes) System.out.printf("%-12s %.2f%n", describe(s), area(s));
}
}
circle 3.14 square 9.00 triangle 12.00 large circle 452.39
Common mistakes
- Overloading by accident –
equals(Point p)instead ofequals(Object o). Use @Override. - Expecting fields or static methods to behave polymorphically.
- Narrowing access or adding checked exceptions in an override.
- Calling overridable methods from constructors.
- Long if/else chains on type instead of an overridden method.
- Thinking overloads are chosen by the run-time type of the argument – they are chosen by its declared type.
Key points to remember
- Overloading = compile time; overriding = run time.
- Dynamic dispatch uses the actual object's class for instance methods.
- Override with the same signature, a same-or-covariant return type, same-or-wider access and no broader checked exceptions.
- final, static and private methods are not overridden.
- Always write @Override.
- Polymorphism replaces type-checking conditionals and makes code open to extension.
Frequently asked questions
Can we override the main method?
main is static, so it can only be hidden, not overridden. It can be overloaded, but the JVM always calls main(String[]).
Is overloading really polymorphism?
Yes – "ad-hoc" or static polymorphism. Run-time polymorphism through overriding is what most people mean in OOP discussions.
Does dynamic dispatch slow programs down?
Barely. The JVM uses virtual method tables and inlines calls it can predict.
Where can I learn more?
Read Java Polymorphism and Java Method Overriding, then practise with the exercises below.