0

Preface: This is an assignment, so that's why I have usernames and passwords as plain text in a CSV file.

Here's what I've been given: username, password, staff type as my data file.

The latter being either E for Employee, M for Manager or C for Contractor. Each of these are represented by their own classes, with their own methods.

I have implemented a function that authenticates the username/password that the user enters. I just now am stuck on how to create an object based off of that last staff type value.

My naive solution at first was to do something like:

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

However I then tried to wrap this in a method, and I'm stuck on what to put as the return type. I've had a year break from Java and OO in general so unfortunately all the concepts of polymorphism, inheritance, generic methods and so on are fuzzy to me.

Obviously in light of this being an assignment I don't want a full implementation, just a hint in the right direction.

Thanks everyone

2 Answers 2

2

You must create an hierarchy, like. for example, Manager and Contractor are both Employees, so they must extend the class Employee. Something like this:

class Employee

class Manager extends Employee

class Contractor extends Employee

That way, you can specify return value as Employee, and return Employee or one of it's subtypes.

Sign up to request clarification or add additional context in comments.

Comments

1

if you find an IS_A relation in these classes (such as Manager is a Employee), then you must use inheritance to implement them:

Class Employee
Class Manager extends Employee

and the return type in this solution is 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;
}

else you can use an interface as return type:

Class Employee implements Createable
Class Manager  implements Createable

and all common methods of Employee and Manager must be define in Createable.

interface Createable {
    void method1()
    ....
}

and then:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.