Polymorphism in Java

Polymorphism means "many forms": the same method call behaves differently depending on the object.

Compile-timeRuntime
Achieved byMethod overloadingMethod overriding
ResolvedBy the compilerBy the JVM at runtime
Also calledStatic bindingDynamic method dispatch

Runtime Polymorphism (Overriding)

Java
class Bank { double rate() { return 0; } String name() { return "Bank"; } }
class SBI  extends Bank { @Override double rate() { return 6.8; } @Override String name() { return "SBI"; } }
class HDFC extends Bank { @Override double rate() { return 7.1; } @Override String name() { return "HDFC"; } }

Bank[] banks = { new SBI(), new HDFC() };
for (Bank b : banks)
    System.out.println(b.name() + " interest: " + b.rate() + "%");
SBI interest: 6.8% HDFC interest: 7.1%

Quick Check

Method overriding is an example of…

Track your progress through the Java course