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.
Size: 36.15 KB
Language: en
Added: Feb 26, 2025
Slides: 10 pages
Slide Content
Polymorphism in Java Understanding Compile-time and Runtime Polymorphism with Examples
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.
Types of Polymorphism in Java 1. Compile-time Polymorphism (Method Overloading) 2. Runtime Polymorphism (Method Overriding)
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.
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"); } }
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.
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(); } }
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.
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.