11-DINAMIC DISPATCH METHOD
11-DINAMIC DISPATCH METHOD
Create an Employee class with data members: name, emp_id and phone. Include get and
display functions in class. Create two subclasses of the employee class: Manager and Cleark.
Include additional data members in Manager: Salary and in Clerk: Years_of_Service.
Implement the scenario using array of Employee class objects and store the data of two
Manager and one Clerk employee. Use dynamic dispatch to call the get and display functions
and display the data of employees. Implement the code in JAVA.
import java.util.Scanner;
// Base class
abstract class Employee {
protected String name;
protected int emp_id;
protected String phone;
// Abstract methods for dynamic dispatch
abstract void getDetails();
abstract void displayDetails();
}
// Manager subclass
class Manager extends Employee {
private double salary;
@Override
void getDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Manager Name: ");
name = sc.nextLine();
System.out.print("Enter Manager ID: ");
emp_id = sc.nextInt();
sc.nextLine(); // Consume newline
System.out.print("Enter Manager Phone: ");
phone = sc.nextLine();
System.out.print("Enter Manager Salary: ");
salary = sc.nextDouble();
}
@Override
void displayDetails() {
System.out.println("Manager Details:");
System.out.println("Name: " + name);
System.out.println("ID: " + emp_id);
System.out.println("Phone: " + phone);
System.out.println("Salary: " + salary);
}
}
// Clerk subclass
class Clerk extends Employee {
private int years_of_service;
@Override
void getDetails() {
Scanner sc = new Scanner(System.in);
System.out.print("Enter Clerk Name: ");
name = sc.nextLine();
System.out.print("Enter Clerk ID: ");
emp_id = sc.nextInt();7254
sc.nextLine(); // Consume newline
System.out.print("Enter Clerk Phone: ");
phone = sc.nextLine();
System.out.print("Enter Clerk Years of Service: ");
years_of_service = sc.nextInt();
}
@Override
void displayDetails() {
System.out.println("Clerk Details:");
System.out.println("Name: " + name);
System.out.println("ID: " + emp_id);
System.out.println("Phone: " + phone);
System.out.println("Years of Service: " + years_of_service);
}
}
// Main class
public class EmployeeManagement {
public static void main(String[] args) {
Employee[] employees = new Employee[3];
// Storing two Managers and one Clerk
employees[0] = new Manager();
employees[1] = new Manager();
employees[2] = new Clerk();
// Get details for each employee
for (Employee emp : employees) {
emp.getDetails();
}
// Display details for each employee
System.out.println("\nDisplaying Employee Details:\n");
for (Employee emp : employees) {
emp.displayDetails();
System.out.println("----------------------");
}
}
}