OOPs

9. Write a Java program to create a class called "Employee" with a name, salary, and hire date attributes, and a method to calculate years of service.

            import java.time.LocalDate;
            import java.time.Period;
            
            class Employee {
                private String name;          // Employee name
                private double salary;        // Employee salary
                private LocalDate hireDate;   // Employee hire date
            
                // Constructor
                public Employee(String name, double salary, LocalDate hireDate) {
                    this.name = name;
                    this.salary = salary;
                    this.hireDate = hireDate;
                }
            
                // Method to calculate years of service
                public int calculateYearsOfService() {
                    LocalDate currentDate = LocalDate.now(); // Get the current date
                    Period period = Period.between(hireDate, currentDate); // Calculate the period
                    return period.getYears(); // Return the number of years
                }
            
                // Method to display employee details
                public void displayDetails() {
                    System.out.println("Name: " + name);
                    System.out.println("Salary: Rs." + salary);
                    System.out.println("Hire Date: " + hireDate);
                    System.out.println("Years of Service: " + calculateYearsOfService());
                }
            }
            
            public class EmployeeManagement {
                public static void main(String[] args) {
                    // Create an Employee object
                    Employee employee = new Employee
                            ("Neha", 50000, LocalDate.of(2015, 9, 15));
            
                    // Display employee details
                    employee.displayDetails();
                }
            }
        

OUTPUT

            Name: Neha
            Salary: Rs. 50000.0
            Hire Date: 2015-09-14
            Years of Service: 9