简体   繁体   中英

Returning the child of an abstract class in Java?

I've been working on a program for staff management, and currently I have a class (HR), an abstract Employee class, with 2 child classes (Manager and SalesPerson). Currently in the HR function, I have a function that should return a type of employee dependent on the user's input, but currently get the error

incompatible types: unexpected return value

Here is the code the other classes.

HR (Function snippet, rather than whole class)

public Employee createNewEmployee(int index)
{
    switch(index)
            {
                case 0:
                    idTracker++;
                    return new Manager(idTracker, nameField.getText(), Double.parseDouble(salaryField.getText()));
                    break;
                case 1:
                    idTracker++;
                    return new SalesPerson(idTracker, nameField.getText(), Double.parseDouble(salaryField.getText()));
                    break;
                default:
                    System.out.println("Didn't work");
            } 
}

Employee class

public abstract class Employee
{
    protected double salary;
    protected String name;
    protected int IDNumber;
    protected String jobTitle;
    protected String dateEmployed;

    public Employee(int ID, String n, double s)
    {
        IDNumber = ID;
        setName(n);
        setSalary(s);
    }
}

And a Salesperson class (manager class is identical, but has a difference in the string jobTitle to show its a manager)

public class SalesPerson extends Employee
{
    public SalesPerson(int ID, String n, double s)
    {
        super(ID, n, s);
        jobTitle = "Sales Person";
    }
}

Any method should always return a value of the declared return type. But there exists in your function createNewEmployee an execution path that do not return any value, compiler then tries to emit a simple return, alas this is not compatible with the declared Employee type. You can add a return null in the default case, for example.

Note that createNewEmployee is unusually badly named, create implies new , then name it createEmployee or newEmployee (the first is the more usual case).

If the error occurs in one of the lines where a new instance is returned (eg return new Manager(...) ), it might indicate that the Employee class expected as the return value is not the same type as the Employee class which is extended by the two subclasses SalesPerson and Manager .

Check the imports in the HR class if the Employee return value is the same as the Employee class extended by the two subclasses. Maybe you imported an Employee class with the same name but from a different package.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM