Runtime Polymorphism

Method overriding and dynamic dispatch

Interview Relevant: Very important concept
6 min read

Runtime Polymorphism

Runtime polymorphism is achieved using method overriding. Method call resolution happens at runtime.

Code Examples

Overridden method invoked at runtime

java
1
2class Animal {
3    void sound() {
4        System.out.println("Animal sound");
5    }
6}
7
8class Dog extends Animal {
9    @Override
10    void sound() {
11        System.out.println("Dog barks");
12    }
13}
14
15Animal a = new Dog();
16a.sound();
17          

Use Cases

  • Framework extension
  • Service implementations
  • Template method pattern

Common Mistakes to Avoid

  • Forgetting @Override
  • Using static methods
  • Wrong method signature