First Week
Employee class with getters and setters, containers, super classes and overriden methodsunknown
java
a month ago
3.2 kB
2
Indexable
Never
package wd; public class Employee { private int id; private String name; private int age; private double salary; private int numOfChildren; //this class will be used as a parent class(super class) //create a subclass for the employees that have children //Constructor public Employee(int id, String name, int age, double salary, int numOfChildren) { this.id = id; this.name = name; this.age = age; this.salary = salary; this.numOfChildren = numOfChildren; } //Getter public int getId(){ return id; //getter returns the same field } //Setter public void setId(int newID){ //setter has to have a parameter, always void id=newID; } public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public double getSalary() { return salary; } public void setSalary(double salary) { this.salary = salary; } public int getNumOfChildren() { return numOfChildren; } public void setNumOfChildren(int numOfChildren) { this.numOfChildren = numOfChildren; } //Calculate salary public double calculateSalary(){ double total; double bonus = 0; if(age >=50){ bonus += 100; } if(numOfChildren > 0){ bonus += numOfChildren * 25; } total=salary + bonus; return total; } @Override public String toString() { return "Employee{" + "id=" + id + ", name='" + name + '\'' + ", age=" + age + ", salary=" + salary + ", numOfChildren=" + numOfChildren + '}'; } } package wd; public class HourlyEmployee extends Employee { private int hours; public HourlyEmployee(int id, String name, int age, double salary, int numOfChildren, int hours) { super(id, name, age, salary, numOfChildren); this.hours=hours; } public int getHours() { return hours; } public void setHours(int hours) { this.hours = hours; } @Override public double calculateSalary(){ double total; total = hours * 20 + getNumOfChildren() * 25; //do it through the getter because num of children field is private return total; } } package wd; public class Main { public static void main(String[] args){ Employee employee1 = new Employee(123, "Larry Smith", 56, 1200, 3); System.out.println(employee1); System.out.println(employee1.calculateSalary()); HourlyEmployee employee2 = new HourlyEmployee(112, "William", 32, 0, 1, 160); System.out.println(employee2); System.out.println(employee2.calculateSalary()); } }
Leave a Comment