Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Lesson 7: Polymorphism, Dynamic Dispatch & Abstract Classes

Lesson 8 of 18 in the free Programming in Java notes on Siksha Sarovar, written by Rohit Jangra.

7.1 Two Flavours of Polymorphism

KindMechanismResolvedAlso called
Compile-timeMethod overloadingBy the compiler from argument typesStatic binding, early binding
RuntimeMethod overridingBy the JVM from the actual objectDynamic dispatch, late binding

7.2 Upcasting & Downcasting

Upcasting (child → parent reference) is implicit and always safe: Animal a = new Dog();. Through a you can call only members declared in Animal — the reference type defines the visible interface, the object type defines the behaviour.

Downcasting (parent reference → child type) needs an explicit cast and is checked at runtime:

Animal a = new Dog();
Dog d = (Dog) a;              // OK: the object really is a Dog
Animal x = new Cat();
Dog bad = (Dog) x;            // compiles, but ClassCastException at runtime!
if (x instanceof Dog dd)      // Java 16 pattern matching: test + cast + bind
    dd.bark();

7.3 Dynamic Method Dispatch — How the JVM Chooses

For a.speak(), the compiler only verifies that the reference type declares speak(). At runtime, the JVM follows the object header to its class metadata and looks up speak in that class's virtual method table (vtable) — each subclass's vtable slot holds a pointer to its own override. This is why the same call site prints different things for Dog and Cat objects.

class Animal { String kind = "Animal"; void speak() { System.out.println("..."); } }
class Dog extends Animal { String kind = "Dog"; void speak() { System.out.println("Woof"); } }

Animal a = new Dog();
a.speak();                     // Woof   -> method: object type (runtime)
System.out.println(a.kind);    // Animal -> FIELD: reference type (compile time)

Trap of the decade: methods are polymorphic, fields are not. Also, private, static, and final methods use static binding — they never dispatch dynamically.

7.4 Abstract Classes — Partial Blueprints

An abstract class cannot be instantiated and may contain both abstract methods (signature only) and concrete methods, fields, constructors, and static members.

abstract class Shape {
    private final String name;
    Shape(String name) { this.name = name; }          // ctor runs via super()
    abstract double area();                            // contract for children
    void describe() {                                  // shared concrete logic
        System.out.printf("%s area = %.2f%n", name, area()); // template pattern
    }
}
class Circle extends Shape {
    private final double r;
    Circle(double r) { super("Circle"); this.r = r; }
    @Override double area() { return Math.PI * r * r; }
}

Rules: a class with even one abstract method must be declared abstract; a subclass must implement all inherited abstract methods or itself be abstract; abstract classes can have constructors (invoked through super() during child construction) but cannot be final (final forbids the extension that abstract requires — contradictory modifiers).

describe() above is the Template Method pattern: the parent fixes the algorithm skeleton, children plug in the varying step — the standard "real use of abstraction" exam answer.

7.5 Abstract Class vs Interface — When to Use Which

CriterionAbstract classInterface
State (instance fields)YesNo (only public static final constants)
ConstructorsYesNo
Method bodiesAnydefault, static, private only
Multiple inheritanceNo (single extends)Yes (implement many)
Access modifiers on membersAll fourMethods implicitly public
Relationship modelledIS-A with shared code/stateCAN-DO capability

Rule of thumb: share code and state among closely related classes → abstract class; define a capability for unrelated classes (Comparable, Runnable, Serializable) → interface.

🎯 Exam Focus

  1. Define runtime polymorphism. Explain dynamic method dispatch with a program and describe how the JVM resolves the call (vtable idea).
  2. Differentiate upcasting and downcasting. When does ClassCastException occur, and how does instanceof (including pattern matching) prevent it?
  3. Why are instance fields not polymorphic? Predict the output of a program where both a field and a method are redefined in the subclass.
  4. What is an abstract class? State four rules governing abstract classes and methods. Can an abstract class have a constructor? Justify.
  5. Compare abstract classes and interfaces (any six points). When would you choose each?
  6. Write a program with abstract class Shape (abstract area(), concrete describe()) and subclasses Circle, Rectangle and Triangle, driven through a Shape[] array.