Bird
Raised Fist0
Javaprogramming~10 mins

Runtime polymorphism in Java - Step-by-Step Execution

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Concept Flow - Runtime polymorphism
Create base class reference
Assign derived class object
Call overridden method
At runtime, JVM decides which method to call
Derived class method executes if overridden
Program continues
At runtime, the program decides which version of an overridden method to call based on the actual object type, not the reference type.
Execution Sample
Java
class Animal {
  void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
  void sound() { System.out.println("Dog barks"); }
}
public class Main {
  public static void main(String[] args) {
    Animal a = new Dog();
    a.sound();
  }
}
This code shows a base class reference holding a derived class object and calling an overridden method, demonstrating runtime polymorphism.
Execution Table
StepActionReference TypeObject TypeMethod CalledOutput
1Create Animal referenceAnimalnullnonenone
2Assign new Dog() to Animal referenceAnimalDognonenone
3Call sound() on Animal referenceAnimalDogDog.sound()Dog barks
4Program continuesAnimalDognonenone
💡 Method call resolved at runtime to Dog's sound() because object type is Dog.
Variable Tracker
VariableStartAfter Step 2After Step 3Final
a (Animal reference)nullDog objectDog objectDog object
Key Moments - 3 Insights
Why does calling sound() on an Animal reference print 'Dog barks' instead of 'Animal sound'?
Because the actual object is a Dog, JVM calls the overridden Dog.sound() method at runtime (see execution_table step 3).
Does the reference type decide which method runs?
No, the reference type only limits accessible methods. The actual method called depends on the object type at runtime (execution_table step 3).
What if Dog did not override sound()?
Then Animal's sound() would run because no overriding method exists in Dog (not shown in table but implied).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what is the object type of variable 'a' after step 2?
AAnimal
Bnull
CDog
DCat
💡 Hint
Check the 'Object Type' column at step 2 in execution_table.
At which step does the method Dog.sound() get called?
AStep 3
BStep 1
CStep 2
DStep 4
💡 Hint
Look at the 'Method Called' and 'Output' columns in execution_table.
If the object assigned to 'a' was new Animal() instead of new Dog(), what would be the output at step 3?
ADog barks
BAnimal sound
CNo output
DCompilation error
💡 Hint
Consider how runtime polymorphism depends on the actual object type shown in variable_tracker.
Concept Snapshot
Runtime polymorphism means the method that runs is decided at runtime based on the object's actual class.
Use a base class reference to hold derived class objects.
Call overridden methods via base reference.
JVM calls the derived class method if overridden.
Reference type limits accessible methods but not which method runs.
Enables flexible and dynamic behavior in programs.
Full Transcript
Runtime polymorphism in Java happens when a base class reference points to a derived class object. When calling an overridden method through this reference, Java decides at runtime which method to execute based on the actual object's class. In the example, an Animal reference holds a Dog object. Calling sound() on this reference runs Dog's version, printing 'Dog barks'. The reference type Animal limits accessible methods but does not decide which method runs. This dynamic method dispatch allows flexible code that can work with different object types through a common interface.

Practice

(1/5)
1. What is runtime polymorphism in Java?
easy
A. Creating multiple objects of the same class
B. Using multiple classes with the same name
C. Choosing which method to call during program execution based on object type
D. Writing methods with different names in the same class

Solution

  1. Step 1: Understand polymorphism concept

    Polymorphism means many forms; in Java, it allows methods to behave differently based on object type.
  2. Step 2: Identify runtime polymorphism

    Runtime polymorphism happens when the program decides which overridden method to call during execution, not before.
  3. Final Answer:

    Choosing which method to call during program execution based on object type -> Option C
  4. Quick Check:

    Runtime polymorphism = method choice at runtime [OK]
Hint: Runtime polymorphism means method choice happens while running [OK]
Common Mistakes:
  • Confusing compile-time and runtime polymorphism
  • Thinking it means multiple classes with same name
  • Believing it is about method overloading
2. Which syntax correctly shows method overriding for runtime polymorphism in Java?
easy
A. class Parent { void show() {} } class Child extends Parent { void show() {} }
B. class Parent { void show() {} } class Child extends Parent { void display() {} }
C. class Parent { void show() {} } class Child { void show() {} }
D. class Parent { void show() {} } class Child extends Parent { void show(int x) {} }

Solution

  1. Step 1: Check method overriding rules

    Method overriding requires same method name and parameters in subclass extending superclass.
  2. Step 2: Match options with overriding

    class Parent { void show() {} } class Child extends Parent { void show() {} } shows subclass overriding show() method correctly; others differ in method name or parameters.
  3. Final Answer:

    class Parent { void show() {} } class Child extends Parent { void show() {} } -> Option A
  4. Quick Check:

    Same method name and parameters in subclass = overriding [OK]
Hint: Overriding needs same method name and parameters in subclass [OK]
Common Mistakes:
  • Changing method name in subclass instead of overriding
  • Changing method parameters (overloading, not overriding)
  • Not extending the parent class
3. What is the output of this code?
class Animal {
  void sound() { System.out.println("Animal sound"); }
}
class Dog extends Animal {
  void sound() { System.out.println("Bark"); }
}
public class Test {
  public static void main(String[] args) {
    Animal a = new Dog();
    a.sound();
  }
}
medium
A. Bark
B. Animal sound
C. Compilation error
D. Runtime error

Solution

  1. Step 1: Understand object and reference types

    Reference is of type Animal, but object is Dog, so overridden method in Dog is called.
  2. Step 2: Identify method called at runtime

    Due to runtime polymorphism, sound() of Dog runs, printing "Bark".
  3. Final Answer:

    Bark -> Option A
  4. Quick Check:

    Overridden method runs based on object type [OK]
Hint: Method called depends on object type, not reference type [OK]
Common Mistakes:
  • Thinking reference type decides method called
  • Expecting superclass method output
  • Confusing compile-time and runtime behavior
4. Find the error in this code related to runtime polymorphism:
class Parent {
  void show() { System.out.println("Parent"); }
}
class Child extends Parent {
  void show(int x) { System.out.println("Child " + x); }
}
public class Test {
  public static void main(String[] args) {
    Parent p = new Child();
    p.show();
  }
}
medium
A. Parent class method show() is private
B. Child class does not override show() method correctly
C. Cannot assign Child object to Parent reference
D. Missing main method

Solution

  1. Step 1: Check method overriding in Child class

    Child defines show(int x), which is overloading, not overriding show().
  2. Step 2: Understand method call on Parent reference

    Parent reference calls show() with no arguments, but Child has no overriding method, so Parent's method runs.
  3. Final Answer:

    Child class does not override show() method correctly -> Option B
  4. Quick Check:

    Overriding needs exact method signature match [OK]
Hint: Overriding needs same method signature, not just same name [OK]
Common Mistakes:
  • Thinking overloading is overriding
  • Expecting Child's show(int) to override show()
  • Ignoring method parameters in overriding
5. Given these classes:
class Vehicle {
  void start() { System.out.println("Vehicle starts"); }
}
class Car extends Vehicle {
  void start() { System.out.println("Car starts"); }
}
class Bike extends Vehicle {
  void start() { System.out.println("Bike starts"); }
}
public class Test {
  public static void main(String[] args) {
    Vehicle[] vehicles = {new Car(), new Bike(), new Vehicle()};
    for (Vehicle v : vehicles) {
      v.start();
    }
  }
}

What is the output when this program runs?
hard
A. Vehicle starts Vehicle starts Vehicle starts
B. Compilation error due to array initialization
C. Car starts Vehicle starts Bike starts
D. Car starts Bike starts Vehicle starts

Solution

  1. Step 1: Analyze array elements and their types

    Array holds objects: Car, Bike, Vehicle, all as Vehicle references.
  2. Step 2: Understand method calls in loop

    Each start() call runs overridden method of actual object type due to runtime polymorphism.
  3. Step 3: Determine output lines

    Car prints "Car starts", Bike prints "Bike starts", Vehicle prints "Vehicle starts" in order.
  4. Final Answer:

    Car starts Bike starts Vehicle starts -> Option D
  5. Quick Check:

    Overridden methods run per object type in array [OK]
Hint: Loop calls overridden methods based on actual object type [OK]
Common Mistakes:
  • Expecting all calls to run Vehicle's method
  • Confusing array reference type with object type
  • Thinking array initialization causes error