前言:这是一个作业,这就是为什么我有用户名和 密码为CSV文件中的纯文本。
以下是我给出的内容:
username, password, staff type
作为我的数据文件。
后者为E
Employee
,M
为Manager
,C
为Contractor
。每个都由他们自己的类表示,并有自己的方法。
我已经实现了一个验证用户输入的用户名/密码的函数。我刚才被困在如何基于最后staff type
值创建对象。
我最初的天真解决方案是做类似的事情:
if (staffType.equals("E")) {
Employee user = new Employee();
else if (staffType.equals("C")) {
Contractor user = new Contractor();
else if (staffType.equals("M")) {
Manager user = new Manager();
}
然而,我尝试将其包装在一个方法中,并且我仍然坚持要作为返回类型放置什么。我从Java和OO那里休息一年,所以不幸的是,多态,继承,泛型方法等所有概念对我来说都是模糊的。
显然,鉴于这是一项任务,我不想要一个完整的实施,只是提示正确的方向。
谢谢大家
答案 0 :(得分:2)
您必须创建层次结构,例如。例如,Manager和Contractor都是Employees,因此他们必须扩展Employee类。 像这样:
class Employee
class Manager extends Employee
class Contractor extends Employee
这样,您可以将返回值指定为Employee,并返回Employee或其中一个子类型。
答案 1 :(得分:1)
如果您在这些类中找到IS_A
关系(例如Manager 是 Employee),那么您必须使用继承来实现它们:
Class Employee
Class Manager extends Employee
,此解决方案中的返回类型为Employee
。
public Employee create(String staffType) {
Employee user = null;
if (staffType.equals("E")) {
user = new Employee();
else if (staffType.equals("M")) {
user = new Manager();
}
....
return user;
}
否则您可以使用接口作为返回类型:
Class Employee implements Createable
Class Manager implements Createable
必须在Employee
中定义Manager
和Createable
的所有常用方法。
interface Createable {
void method1()
....
}
然后:
public Employee create(String staffType) {
Creatable user = null;
if (staffType.equals("E")) {
user = new Employee();
else if (staffType.equals("M")) {
user = new Manager();
}
....
return user;
}