Polymorphism in Java
Polymorphism in Java is one of the core
concepts of object-oriented programming
(OOP). It allows objects to be treated as
instances of their parent class rather than their
actual class. The word “polymorphism” means
“many forms,” and in Java, it allows a single
action to behave differently based on the object
performing it.
Introduction to Polymorphism
Core Concept Key Benefit
Polymorphism allows -> Enables code reusability by using
a single interface to common interfaces for different
have multiple objects.
implementations. -> Improves flexibility by allowing
This means the same new behaviors without changing
method name can existing code.
produce different ->Supports scalability as new
results. classes can be added with minimal
changes.
->Enhances maintainability through
cleaner and organized code
structure.
Types of Polymorphism
Run-Time
Compile-Time Also known as dynamic
Also known as static
polymorphism. Method
polymorphism. Method
overriding and interfaces
overloading is a common
demonstrate run-time
example.
polymorphism.
Compile-Time
Polymorphism
1 Method Overloading 2 Compiler Resolution
Method overloading is when a The compiler selects the
class has multiple methods appropriate method. The
with the same name but selection is based on
different parameters (number, argument types during
type, or order). It allows you compilation.
to define multiple ways to
perform a similar operation.
3 Static Binding
Static binding means the method call is resolved by the compiler at
compile time. It occurs when the type of the object is known at compile
time — typically with method overloading, private, final, or static
methods.
Example: Method
Overloading
class Calculator {
int add(int a, int b) {
return a + b;
}
double add(double a, double b) {
return a + b;
}
}
Calculator calc = new Calculator();
[Link](2, 3); // Calls int add()
[Link](2.5, 3.5); // Calls double add()
Runtime Polymorphism
(Method Overriding)
Inheritance
Requires a superclass and a subclass. The subclass
inherits from the superclass.
Overriding
The subclass provides a specific implementation.
Overriding a method in the superclass.
Dynamic Binding
The method to call is determined at runtime. Decided
based on the object's actual type.
Example: Method
Overriding
class Animal {void sound() {
[Link]("Animal makes a sound");
}
}
class Dog extends Animal {
@Override
void sound() {
[Link]("Dog barks");
}
}
public class Main {
public static void main(String[] args) {
Animal animal = new Animal();
Animal dog = new Dog();
[Link](); // Calls Animal's sound method
[Link]();
}
}