Polymorphism, derived from Greek, means "many forms." In Java, it allows a single interface to represent different underlying data types. This means that a method can perform different tasks based on the object that invokes it.
2. What is Polymorphism?
• Polymorphism allows one interface to be used
for different data types or actions.
• In Java, it helps in achieving flexibility and
reusability of code.
3. Types of Polymorphism in Java
• 1. Compile-time Polymorphism (Method
Overloading)
• 2. Runtime Polymorphism (Method
Overriding)
4. Compile-time Polymorphism
(Method Overloading)
• • Achieved using method overloading.
• • Methods have the same name but different
parameters.
• • The method to be executed is determined at
compile time.
5. Example: Method Overloading in
Java
class OverloadExample {
void display(int a) {
System.out.println("Integer: " + a);
}
void display(String a) {
System.out.println("String: " + a);
}
public static void main(String args[]) {
OverloadExample obj = new OverloadExample();
obj.display(10);
obj.display("Java");
}
}
6. Runtime Polymorphism (Method
Overriding)
• • Achieved using method overriding.
• • A subclass provides a specific
implementation of a method already defined
in its parent class.
• • The method to be executed is determined at
runtime.
7. Example: Method Overriding in
Java
class Parent {
void show() {
System.out.println("Parent class method");
}
}
class Child extends Parent {
void show() {
System.out.println("Child class method");
}
public static void main(String args[]) {
Parent obj = new Child();
obj.show();
}
}
8. Key Differences: Overloading vs
Overriding
• • Overloading happens at compile time,
Overriding happens at runtime.
• • Overloading is within the same class,
Overriding involves inheritance.
• • Overloaded methods have different
parameters, Overridden methods have the
same signature.
9. Summary
• • Polymorphism allows flexibility and
reusability in code.
• • Two types: Compile-time (Method
Overloading) and Runtime (Method
Overriding).
• • Helps in writing cleaner and scalable
programs.