3. Introduction to
Polymorphism
Polymorphism in Java is one of the four fundamental
principles of object-oriented programming (OOP), along with
encapsulation, inheritance, and abstraction. Polymorphism
allows objects of different types to be treated as objects of a
common type.
3
4. Types of Polymorphism
• There are two types of polymorphism in Java. They are:
• Compile-Time (or Static) Polymorphism
• Runtime (or Dynamic) Polymorphism.
4
5. Compile-Time Polymorphism
• Compile-time polymorphism is achieved through method
overloading.
• A class can have multiple methods with the same name but
different parameters (number or type).
• The compiler determines which method to call based on the
method signature during compile-time.
5
6. Example for Compile-Time Polymorphism
public class Calculator {
public int add(int a, int b) {
return a + b;
}
public double add(double a, double b) {
return a + b;
}
}
6
7. Runtime Polymorphism
• Runtime polymorphism is achieved through method
overriding.
• A subclass provides a specific implementation for a method
that is already defined in its superclass.
• The decision about which method to call is made at runtime
based on the actual type of the object.
7
8. Example for Runtime Polymorphism
class Animal {
void makeSound() {
System.out.println("Some generic sound");
}
}
class Dog extends Animal {
void makeSound() {
System.out.println("Bark");
}
}
class Cat extends Animal {
void makeSound() {
System.out.println("Meow");
}
}
8