Coding Techniques
Polymorphism and Method Overriding · Study material
Replacing conditionals with polymorphism
When code branches on "what kind of thing is this?", move each branch into a class of its own. Adding a new kind then means adding a class, not editing every if/else.
import java.util.List;
public class Main {
// ✘ Without polymorphism: every new type means editing this method
static double shippingIf(String type, double kg) {
if (type.equals("standard")) return 40 + 10 * kg;
else if (type.equals("express")) return 80 + 20 * kg;
else if (type.equals("pickup")) return 0;
throw new IllegalArgumentException(type);
}
// ✔ With polymorphism: each type knows its own rule; new types need no changes here
interface Shipping { double cost(double kg); String name(); }
static class Standard implements Shipping { public double cost(double kg) { return 40 + 10 * kg; } public String name() { return "standard"; } }
static class Express implements Shipping { public double cost(double kg) { return 80 + 20 * kg; } public String name() { return "express"; } }
static class Pickup implements Shipping { public double cost(double kg) { return 0; } public String name() { return "pickup"; } }
public static void main(String[] args) {
for (Shipping s : List.of(new Standard(), new Express(), new Pickup())) {
System.out.println(s.name() + " " + s.cost(2.5) + " " + (s.cost(2.5) == shippingIf(s.name(), 2.5)));
}
}
}
standard 65.0 true express 130.0 true pickup 0.0 true
Overriding equals, hashCode and toString correctly
final class Point {
private final int x, y;
Point(int x, int y) { this.x = x; this.y = y; }
@Override // Object.equals takes an Object – not a Point!
public boolean equals(Object o) {
if (this == o) return true;
if (!(o instanceof Point p)) return false;
return x == p.x && y == p.y;
}
@Override public int hashCode() { return 31 * x + y; } // always together with equals
@Override public String toString() { return "(" + x + ", " + y + ")"; }
} Programming to the supertype
// ✔ Declare variables, parameters and return types with the most general useful type
List<String> names = new ArrayList<>(); // can switch to LinkedList without other changes
Map<String, Integer> stock = new HashMap<>();
void notifyAll(Collection<? extends Notifier> notifiers) { … }
Payment choosePayment(String mode) { … } // returns UpiPayment, CardPayment …
// ✘ Tied to one implementation
ArrayList<String> names2 = new ArrayList<>(); Polymorphism checklist
- Put @Override on every overriding method.
- Keep the overriding method's contract: same meaning, no surprises (Liskov).
- Use super.method() to extend behaviour.
- Do not rely on fields or static methods behaving polymorphically.
- Program to interfaces and superclasses.
- Prefer overriding over instanceof chains; use sealed types + switch when operations vary more than types.