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) {
[Link] = id;
[Link] = name;
}
public void displayInfo() {
[Link]("Employee ID: " + id + ", Name: " + name);
}
// Method Overloading (Compile-time polymorphism)
public void work() {
[Link](name + " is working.");
}
public void work(int hours) {
[Link](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() {
[Link]("Manager ID: " + [Link] + ", Name: " + [Link]);
}
@Override
public void work() {
[Link]([Link] + " 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");
[Link]();
[Link]();
[Link](8);
[Link]();
// Runtime polymorphism: method overriding
Employee e2 = new Manager(102, "Bob"); // Reference type Employee,
object type Manager
[Link](); // Calls overridden method in Manager
[Link](); // 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.