基于CSV文件中的变量创建对象

时间:2014-10-11 05:14:57

标签: java oop

  

前言:这是一个作业,这就是为什么我有用户名和   密码为CSV文件中的纯文本。

以下是我给出的内容: username, password, staff type作为我的数据文件。

后者为E EmployeeMManagerCContractor。每个都由他们自己的类表示,并有自己的方法。

我已经实现了一个验证用户输入的用户名/密码的函数。我刚才被困在如何基于最后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那里休息一年,所以不幸的是,多态,继承,泛型方法等所有概念对我来说都是模糊的。

显然,鉴于这是一项任务,我不想要一个完整的实施,只是提示正确的方向。

谢谢大家

2 个答案:

答案 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中定义ManagerCreateable的所有常用方法。

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;
}