Method Overriding, Dynamic Method Dispatch (Runtime Polymorphism) & Overloading vs Overriding
1. Topic Introduction
Dynamic Method Dispatch—powered by Method Overriding—is the crown jewel of Object-Oriented Programming in Java. It allows you to write general algorithms against a single superclass (Figure or Shape) while subclasses (Rectangle, Triangle) supply specialized implementations selected automatically at runtime!
Area()) Controlling Multiple DevicesSuppose you write Figure fig;—a single remote control (superclass reference). If you point that remote at a Rectangle object and press fig.area(), Java executes length * breadth. Next, you point the exact same fig variable at a Triangle object and press fig.area()—now Java executes 0.5 * base * height! Notice that at compile time, javac only knew fig had type Figure. It was the JVM at runtime inspecting the actual object on the Heap that picked the right area()!
3. Essential Exam Definitions
4. Detailed Technical Explanation & Syntax
1. Rules of Method Overriding (KTU Exam Checklist)
To override properly (instead of accidentally overloading!), observe these mandatory Java rules:
- 1. Identical Signature: Name and parameter types/count/order MUST match identically (if parameters differ, it becomes Method Overloading!).
- 2.
@OverrideAnnotation: Strongly recommended sojavaccatches typos at compile time. - 3. Return Type: Must be identical or a covariant subtype (subclass of parent's return type).
- 4. Access Modifier Rule: Subclass CANNOT assign a weaker access modifier (e.g., overriding a
publicparent method asprotectedorprivateis a COMPILE ERROR; wideningprotected->publicis allowed). - 5. Cannot Override
private,static, orfinalmethods! (privateis invisible to subclass;staticmethods belong to class so redefining them is method hiding, NOT overriding;finalforbids overriding). - 6. Exception Rule: Overriding method cannot throw broader checked exceptions than the parent method declares.
- 7. Accessing Parent Version: Inside subclass,
super.show()invokes the superclass's overridden version.
2. Why Overridden Methods Matter ('One Interface, Multiple Methods')
Overridden methods allow a general superclass to declare a common interface (area(), callme(), calculateTax()) shared across all derivatives while giving each subclass total freedom to specialize its behavior. New subclasses can be plugged in later without rewriting existing caller code!
5. Working Principle: Runtime Resolution in Dynamic Method Dispatch
- 1. Compile Time:
A r = new B(); r.callme();—javacchecks ONLY whether classAdeclarescallme(). (IfBdefines a brand-new method not inA,r.onlyInB()fails compilation!). - 2. Runtime: JVM follows
rto the Heap object (new B()), checks its runtime class table (B), and dispatchesB.callme()instead ofA.callme(). - 3. Note: Instance variables are NOT polymorphic! Accessing
r.fieldalways readsA's field (resolved by reference type, not object type).
6. Examination-Ready Diagrams
Dynamic Method Dispatch (Runtime Polymorphism)
Shows how a single superclass reference variable (Figure ref or A r) points to different subclass objects at runtime, causing the JVM to select the overridden method dynamically based on the actual object type.
- Superclass Reference (
A r): Compile-time type checks thatcallme()exists inA. - Runtime Binding: JVM inspects the actual Heap object (
A,B, orC) referenced byr. - Overridden Implementations: Executes
A.callme(),B.callme(), orC.callme()respectively.
A r;creates a superclass reference on Stack.r = new A(); r.callme();-> JVM dispatchesA's version.r = new B(); r.callme();-> JVM dispatchesB's overridden version.r = new C(); r.callme();-> JVM dispatchesC's overridden version.
- Draw Stack reference
A ron the left. - Draw three Heap objects on the right:
Object of A,Object of B (extends A),Object of C (extends A), each containing itscallme()method. - Draw three state arrows from
rshowing runtime switching and label: 'Resolved at Runtime by Actual Object Type, NOT Reference Type'.
7. Complete Java Code Examples & Tracing
Figure, Rectangle, and Triangle resolved dynamically at runtime through a single Figure ref variable.| 1 | class Figure { |
| 2 | double dim1, dim2; |
| 3 | |
| 4 | Figure(double a, double b) { |
| 5 | dim1 = a; |
| 6 | dim2 = b; |
| 7 | } |
| 8 | |
| 9 | double area() { |
| 10 | System.out.println("Area for generic Figure is undefined."); |
| 11 | return 0; |
| 12 | } |
| 13 | } |
| 14 | |
| 15 | class Rectangle extends Figure { |
| 16 | Rectangle(double a, double b) { |
| 17 | super(a, b); |
| 18 | } |
| 19 | |
| 20 | @Override |
| 21 | double area() { |
| 22 | System.out.println("Inside Area for Rectangle:"); |
| 23 | return dim1 * dim2; |
| 24 | } |
| 25 | } |
| 26 | |
| 27 | class Triangle extends Figure { |
| 28 | Triangle(double a, double b) { |
| 29 | super(a, b); |
| 30 | } |
| 31 | |
| 32 | @Override |
| 33 | double area() { |
| 34 | System.out.println("Inside Area for Triangle:"); |
| 35 | return (dim1 * dim2) / 2.0; |
| 36 | } |
| 37 | } |
| 38 | |
| 39 | public class DynamicDispatchDemo { |
| 40 | public static void main(String[] args) { |
| 41 | Figure f = new Figure(10, 10); |
| 42 | Rectangle r = new Rectangle(9, 5); |
| 43 | Triangle t = new Triangle(10, 8); |
| 44 | |
| 45 | Figure figRef; // Superclass reference variable |
| 46 | |
| 47 | figRef = r; |
| 48 | System.out.println("Area = " + figRef.area()); |
| 49 | |
| 50 | figRef = t; |
| 51 | System.out.println("Area = " + figRef.area()); |
| 52 | |
| 53 | figRef = f; |
| 54 | System.out.println("Area = " + figRef.area()); |
| 55 | } |
| 56 | } |
Inside Area for Rectangle: Area = 45.0 Inside Area for Triangle: Area = 40.0 Area for generic Figure is undefined. Area = 0.0
extendssuper@Overridedouble- Changing parameter list in subclass (
double area(int scale)) thinking it overrides—that OVERLOADS instead! - Lowering visibility when overriding (parent
public void show()overridden asvoid show()-> compile error). - Assuming
staticmethods undergo dynamic dispatch (static methods bind at compile time based on reference type!).
Comparison Tables
| Comparison Basis | Method Overloading | Method Overriding |
|---|---|---|
| Definition | Multiple methods with same name & DIFFERENT parameters | Subclass redefines superclass method with IDENTICAL signature |
| Class Relationship | Usually within the SAME class | Requires Inheritance (extends superclass/subclass) |
| Parameters | MUST be different (count, type, or order) | MUST be identical |
| Return Type | Can be same or different (does not affect resolution) | Must be same or covariant subtype |
| Binding Time | Compile-time (Static / Early Binding) | Runtime (Dynamic / Late Binding via Dispatch) |
private/static/final | CAN be overloaded | CANNOT be overridden |
| Polymorphism Type | Compile-time Polymorphism | Runtime Polymorphism |
Real-World Applications
- Plugin architectures, payment processors, and GUI component rendering (
paintComponent(Graphics g)overridden by custom Swing panels).
Important KTU Exam Points
- Memorize the full 7-row Overloading vs Overriding table!
- When writing Dynamic Method Dispatch for 9 marks, ALWAYS include: Principle ('superclass reference refers to subclass object'), Resolution rule ('actual object type, NOT reference type'), Diagram 7, and the
Figure/Rectangle/TriangleorA/B/Ccode!
Memory Techniques & Revision
- Dynamic Dispatch Golden Sentence: 'Object Type decides the Method; Reference Type checks Visibility at Compile Time.'
Common Pitfalls to Avoid
- Writing
publicparent method and forgettingpublicon the overriding subclass method.
KTU-Style Questions & Exam-Ready Answers
Structured specifically for KTU Part A (3-mark) and Part B (6/9-mark) evaluation rubrics.
Introduction: Dynamic Method Dispatch is the mechanism by which Java resolves calls to an overridden method at run time rather than compile time, implementing runtime polymorphism.
- Core Principle: A superclass reference variable can refer to a subclass object (
Figure ref = new Rectangle(9, 5);). - Runtime Selection: When
ref.area()is called, the JVM inspects the actual Heap object type referenced byref(notref's declared reference type) and invokes that class's overridden version. - Significance: Implements OOP's 'one interface, multiple methods' design, enabling extensible code reuse and robustness.
A r pointing dynamically to Heap objects of A, B, C). Include Figure/Rectangle/Triangle code.Quick Understanding Check
1. Given class Parent { void show() { print("P"); } } and class Child extends Parent { void show() { print("C"); } }, what does Parent p = new Child(); p.show(); print?
2. Which type of method CANNOT be overridden in a subclass?