Polymorphism in Java
Polymorphism means "many forms": the same method call behaves differently depending on the object.
| Compile-time | Runtime | |
|---|---|---|
| Achieved by | Method overloading | Method overriding |
| Resolved | By the compiler | By the JVM at runtime |
| Also called | Static binding | Dynamic method dispatch |
Runtime Polymorphism (Overriding)
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