Polymorphism Using Methods
1. Two Kinds (beginner map!)
Compile-time (overloading: same name, different params — compiler picks!) vs Runtime (overriding: child remakes parent method — JVM picks by OBJECT!). Runtime = true polymorphism!
class Calc {
int add(int a, int b) { return a + b; }
double add(double a, double b) { return a + b; } // same name, different params!
int add(int a, int b, int c) { return a + b + c; }
}
calc.add(1, 2); // int version (compiler picks by args!)
calc.add(1.5, 2.5); // double version!
4. Rules (exam traps!)
- Overriding needs SAME signature + IS-A + non-static + non-private + covariant return ok.
@Overrideannotation catches typos (soud()→ error!).- Overloading ≠ overriding (table: binding time, signature, class!).
5. Exam Points
- Overload vs override table + program — 7-10 marks, #1 polymorphism Q.
- Runtime trace (
a.sound()→ ?) — 5 marks, very frequent.