Employee Class) Create a class called Employee that includes three instance vari
ID: 3902390 • Letter: E
Question
Employee Class) Create a class called Employee that includes three instance variables—a first
name (type String), a last name (type String) and a monthly salary (double). Provide a constructor
that initializes the three instance variables. Provide a set and a get method for each instance variable. If
the monthly salary is not positive, do not set its value. Write a test application named EmployeeTest
that demonstrates class Employee’s capabilities. Create two Employee objects and display each object’s
yearly salary. Then give each Employee a 10% raise and display each Employee’s yearly salary again.
Explanation / Answer
public class Employee { private String first, last; private double salary; public Employee(String first, String last, double salary) { if(salary < 0) { salary = 0; } this.first = first; this.last = last; this.salary = salary; } String getFirst() { return first; } void setFirst(String first) { this.first = first; } String getLast() { return last; } void setLast(String last) { this.last = last; } double getMonthlySalary() { return salary; } double getYearlySalary() { return 12*salary; } void setSalary(double salary) { if(salary < 0) { return; } this.salary = salary; } @Override public String toString() { return "Employee [first=" + first + ", last=" + last + ", salary=" + salary + "]"; } public void giveRaise(double perc) { salary = salary + salary * perc / 100; } } public class EmployeeTest { public static void main(String[] args) { Employee e1 = new Employee("f1", "l1", 120); Employee e2 = new Employee("f2", "l2", 220); System.out.println(e1); System.out.println("Yearly Salary: " + e1.getYearlySalary()); System.out.println("Giving raise of 10% to e1."); e1.giveRaise(10); System.out.println(e1); System.out.println("Yearly Salary: " + e1.getYearlySalary()); System.out.println(" Employee 2: "); System.out.println(e2); System.out.println("Yearly Salary: " + e2.getYearlySalary()); } }Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.