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).