1.
Compile-time Polymorphism (Method Overloading)
• Achieved using method overloading, where multiple methods have the same name but
different parameters.
• The method to be executed is decided at compile time.
Code:
class CompileTimePoly {
// Method Overloading
void display(int a) {
System.out.println("Integer value: " + a);
void display(double a) {
System.out.println("Double value: " + a);
void display(String a) {
System.out.println("String value: " + a);
public class PolymorphismExample1 {
public static void main(String[] args) {
CompileTimePoly obj = new CompileTimePoly();
obj.display(10); // Calls display(int)
obj.display(3.14); // Calls display(double)
obj.display("Hello"); // Calls display(String)
}
Output:
Integer value: 10
Double value: 3.14
String value: Hello
2. Runtime Polymorphism (Method Overriding)
• Achieved using method overriding, where a subclass provides a specific implementation of a
method already defined in its parent class.
• The method to be executed is determined at runtime based on the actual object.
Code:
class Parent {
void show() {
System.out.println("Parent class method");
class Child extends Parent {
@Override
void show() {
System.out.println("Child class method (Overridden)");
public class PolymorphismExample2 {
public static void main(String[] args) {
Parent obj1 = new Parent(); // Parent reference, Parent object
obj1.show(); // Calls Parent's show()
Parent obj2 = new Child(); // Parent reference, Child object
obj2.show(); // Calls Child's overridden show() at runtime
}
}
Output:
Parent class method
Child class method (Overridden)