Here’s a single Java program demonstrating compile-time polymorphism (method overloading), runtime
polymorphism (method overriding), and the concept of polymorphism. You can run this in CodeRunner or
any Java IDE.
// Employee class for demonstration
class Employee {
private int id;
private String name;
public Employee(int id, String name) {
this.id = id;
this.name = name;
}
public void displayInfo() {
System.out.println("Employee ID: " + id + ", Name: " + name);
}
// Method Overloading (Compile-time polymorphism)
public void work() {
System.out.println(name + " is working.");
}
public void work(int hours) {
System.out.println(name + " is working for " + hours + " hours.");
}
}
// Subclass for Runtime Polymorphism (Method Overriding)
class Manager extends Employee {
public Manager(int id, String name) {
super(id, name);
}
@Override
public void displayInfo() {
System.out.println("Manager ID: " + super.id + ", Name: " + super.name);
}
@Override
public void work() {
System.out.println(super.name + " is managing the team.");
}
}
public class Main {
1
public static void main(String[] args) {
// Compile-time polymorphism: method overloading
Employee e1 = new Employee(101, "Alice");
e1.displayInfo();
e1.work();
e1.work(8);
System.out.println();
// Runtime polymorphism: method overriding
Employee e2 = new Manager(102, "Bob"); // Reference type Employee,
object type Manager
e2.displayInfo(); // Calls overridden method in Manager
e2.work(); // Calls overridden work method in Manager
}
}
Expected Output:
Employee ID: 101, Name: Alice
Alice is working.
Alice is working for 8 hours.
Manager ID: 102, Name: Bob
Bob is managing the team.
Explanation: - work() and work(int hours) → demonstrate compile-time polymorphism
(overloading). - displayInfo() and work() overridden in Manager → demonstrate runtime
polymorphism (overriding). - Using a common reference type ( Employee ) for a Manager object
demonstrates polymorphism in practice.