KTU OOP Java2024 Scheme • 60M ESE
MODULE 2/Section 2: Inheritance

Method Overriding, Dynamic Method Dispatch (Runtime Polymorphism) & Overloading vs Overriding

HIGH PRIORITY (Prep Guide)Official Syllabus~18 min study
Official KTU 2024 Syllabus Topics Covered Here
Method overridingRules of method overridingDynamic method dispatchRuntime method selectionOverloading versus 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!

2. Start From Zero: One Universal Remote Button (Area()) Controlling Multiple Devices

Suppose 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()!

Key Takeaway: In Dynamic Method Dispatch, it is the actual type of the Heap object being referred to—NOT the type of the reference variable—that determines which overridden method runs at runtime!

3. Essential Exam Definitions

Method Overriding
Defining a method in a subclass with the exact same name, parameter signature, and compatible (same or covariant) return type as a method in its superclass, replacing the superclass implementation for subclass objects.
Dynamic Method Dispatch
Runtime polymorphism mechanism whereby a call to an overridden method through a superclass reference variable is resolved by the JVM at runtime based on the actual object type being referenced.

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. @Override Annotation: Strongly recommended so javac catches 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 public parent method as protected or private is a COMPILE ERROR; widening protected -> public is allowed).
  • 5. Cannot Override private, static, or final methods! (private is invisible to subclass; static methods belong to class so redefining them is method hiding, NOT overriding; final forbids 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. 1. Compile Time: A r = new B(); r.callme(); — javac checks ONLY whether class A declares callme(). (If B defines a brand-new method not in A, r.onlyInB() fails compilation!).
  2. 2. Runtime: JVM follows r to the Heap object (new B()), checks its runtime class table (B), and dispatches B.callme() instead of A.callme().
  3. 3. Note: Instance variables are NOT polymorphic! Accessing r.field always reads A's field (resolved by reference type, not object type).

6. Examination-Ready Diagrams

Diagram 7

Dynamic Method Dispatch (Runtime Polymorphism)

Superclass ReferenceA r; (Compile-time type: A)Object of A (r = a)Calls A.callme()Object of B (r = b)Calls B.callme() [Overridden]Object of C (r = c)Calls C.callme() [Overridden]JVM RuntimeSelects method by Object type, NOT Ref type

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.

Key Components
  • Superclass Reference (A r): Compile-time type checks that callme() exists in A.
  • Runtime Binding: JVM inspects the actual Heap object (A, B, or C) referenced by r.
  • Overridden Implementations: Executes A.callme(), B.callme(), or C.callme() respectively.
Step-by-Step Flow
  1. A r; creates a superclass reference on Stack.
  2. r = new A(); r.callme(); -> JVM dispatches A's version.
  3. r = new B(); r.callme(); -> JVM dispatches B's overridden version.
  4. r = new C(); r.callme(); -> JVM dispatches C's overridden version.
How to Draw in KTU Exam
  • Draw Stack reference A r on the left.
  • Draw three Heap objects on the right: Object of A, Object of B (extends A), Object of C (extends A), each containing its callme() method.
  • Draw three state arrows from r showing runtime switching and label: 'Resolved at Runtime by Actual Object Type, NOT Reference Type'.

7. Complete Java Code Examples & Tracing

Method Overriding (`super.show()`) + Dynamic Method Dispatch (`Figure` Hierarchy)DynamicDispatchDemo.java
Complete KTU exam example combining Figure, Rectangle, and Triangle resolved dynamically at runtime through a single Figure ref variable.
1class 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
15class 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
27class 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
39public 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}
Expected Output
Inside Area for Rectangle:
Area = 45.0
Inside Area for Triangle:
Area = 40.0
Area for generic Figure is undefined.
Area = 0.0
Keywords:extendssuper@Overridedouble
Common Exam & Coding Mistakes
  • Changing parameter list in subclass (double area(int scale)) thinking it overrides—that OVERLOADS instead!
  • Lowering visibility when overriding (parent public void show() overridden as void show() -> compile error).
  • Assuming static methods undergo dynamic dispatch (static methods bind at compile time based on reference type!).

Comparison Tables

Method Overloading vs Method Overriding (Top KTU 6-Mark Comparison!)
Comparison BasisMethod OverloadingMethod Overriding
DefinitionMultiple methods with same name & DIFFERENT parametersSubclass redefines superclass method with IDENTICAL signature
Class RelationshipUsually within the SAME classRequires Inheritance (extends superclass/subclass)
ParametersMUST be different (count, type, or order)MUST be identical
Return TypeCan be same or different (does not affect resolution)Must be same or covariant subtype
Binding TimeCompile-time (Static / Early Binding)Runtime (Dynamic / Late Binding via Dispatch)
private/static/finalCAN be overloadedCANNOT be overridden
Polymorphism TypeCompile-time PolymorphismRuntime 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/Triangle or A/B/C code!

Memory Techniques & Revision

  • Dynamic Dispatch Golden Sentence: 'Object Type decides the Method; Reference Type checks Visibility at Compile Time.'

Common Pitfalls to Avoid

  • Writing public parent method and forgetting public on 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 by ref (not ref'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.
Exam Diagram Note: Draw Diagram 7 (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?