Java Encapsulation: Implementing an Employee Class with Getter and Setter Methods
Write a Java program to create a class called Employee with private instance variables employee_id, employee_name, and employee_salary. Provide public getter and setter methods to access and modify the id and name variables, but provide a getter method for the salary variable that returns a formatted string.
Sample Solution:
Java Code:
Explanation:
In the aboove code, the Employee class encapsulates the private instance variables employee_id, employee_name, and employee_salary. The getEmployeeId() and getEmployeeName() methods are public getter methods that allow other classes to access employee_id and employee_name values, respectively. The setEmployeeId() and setEmployeeName() methods are public setter methods that allow other classes to modify employee_id and employee_name values.
The getEmployeeSalary() method is another public getter method that returns employee_salary. However, we have also added an additional method getFormattedSalary() that returns a formatted string representation of the salary. This method provides a formatted version of the salary value, adding a dollar sign and two decimal places.
In the Main class, an employee object within the Employee class is created. The setter methods (setEmployeeId(), setEmployeeName(), and setEmployeeSalary()) are used to set employee_id, employee_name, and employee_salary, respectively. The getter methods (getEmployeeId(), getEmployeeName(), and getFormattedSalary()) are used to retrieve employee_id, employee_name, and formatted salary, respectively.
Finally, System.out.println() statements print employee_id, employee_name, and formatted salary.
Output:
Employee Details: ID: 15 Name: Caelius Dathan Salary: $4900.00
Flowchart:
For more Practice: Solve these Related Problems:
- Write a Java program where the "Employee" class prevents setting a salary below minimum wage.
- Write a Java program where the "Employee" class allows salary increments but not decrements.
- Write a Java program where the "Employee" class includes a method to determine the years of service.
- Write a Java program where the "Employee" class allows assigning a department with predefined values only.
Go to:
Java Code Editor:
Improve this sample solution and post your code through Disqus
PREV : Implementing a circle class with getter, setter, and calculation methods.
NEXT : Implementing a circle class with getter, setter, and calculation methods.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.