Main方法import java.util.Scanner;
public class HW4 {
public static int idScan() {
Scanner x = new Scanner(System.in);
int id = x.nextInt();
return id;
}
public static double salaryScan() {
Scanner y = new Scanner(System.in);
double salary = y.nextInt();
return salary;
}
public static int statusScan() {
Scanner z = new Scanner(System.in);
int status = z.nextInt();
return status;
}
public static void main(String args[]) {
Employee [] employee = new Employee[10];
employee [0] = new Employee(1, 0, 0);
employee [1] = new Employee(1, 0, 0);
employee [2] = new Employee(1, 0, 0);
employee [3] = new Employee(1, 0, 0);
employee [4] = new Employee(1, 0, 0);
employee [5] = new Employee(1, 0, 0);
employee [6] = new Employee(1, 0, 0);
employee [7] = new Employee(1, 0, 0);
employee [8] = new Employee(1, 0, 0);
employee [9] = new Employee(1, 0, 0);
for(Employee e : employee) {
System.out.println("Enter emplpoyee ID of an employee?");
int id = idScan();
System.out.println("Enter salary of the employee?");
double sal = salaryScan();
System.out.println("Is this employee a manager or worker? (Enter 1 for worker and 2 for manager)");
int stat = statusScan();
}
}
字符集
}
public class MyClass {
private int employeeID;
private double salary;
private int status;
//Constructor
public Employee(int ID, double esalary, int estat) {
employeeID = ID;
esalary = salary;
status = estat;
}
//Getter ID
public int getID() {
return employeeID;
}
//Setter ID
public void setID(int ID) {
employeeID = ID;
}
//Getter Salary
public double getSalary() {
return salary;
}
//Setter Salary
public void setSalary(double esalary) {
salary = esalary;
}
//Getter Status
public double getStatus() {
return status;
}
//Setter Status
public void setStatus(int estat) {
status = estat;
}
型
}
ManagerEmployee.javapublic class ManagerEmployee扩展Employee {
//Super Constructor
public ManagerEmployee(int ID, double esalary, int estat) {
super(ID, esalary, estat = 1);
}
型
}
public class WorkerEmployee extends Employee {
//Super Constructor
public WorkerEmployee(int ID, double esalary, int estat) {
super(ID, esalary, estat = 2);
}
型
}
我正在做的程序涉及通过扫描仪输入两种类型的员工计算员工的工资(经理/工人)。有一个部分让我很纠结,那就是我需要输入一个数字来表示工人或经理(工人1人,经理2人)我通常对需要在哪里建立规则感到困惑,是在Employee类中还是在两个子类中。
2条答案
按热度按时间rwqw0loc1#
我认为你正在尝试实现一个工厂模式。在这种情况下,你可以使
Employee
类abstract
。因为不会有Employee
谁只是一个Employee
。它必须是一个Manager
或Worker
。因为你使用多态性,您不需要将status
保留在Employee
类中。您可以通过其类型找到它是什么类型的雇员。因此,您的类层次结构变为Employee.java
字符集
ManagerEmployee.java
型
WorkerEmployee.java
型
在main方法中,您应该在检查用户输入之后创建特定的员工。
HW4.java
型
或者,我们可以使用
enum
并删除子类,因为它们不会向Employee
类添加任何属性/功能。在这种情况下,Employee.java
型
你的
main
方法将变成型
它类似于您当前的方法,但使用
enum
代替int
,因此任何任意值都不能被分配为status
。bihw5rsg2#
根据 stat 是 1 还是 2,创建 Worker 或 Manager 类。
字符集