Reputation: 1
I have a simple question I can't find the answer for. I have this entries added to a list:
Employee.add(new BackEndDeveloper(100, "Emmanuel", "Santana"));
Employee.add(new FrontEndDeveloper(100, "Luis", "Valero"));
Employee.add(new Intern(10, "Erick", "Lara"));
And I need to retrieve the following info:
"Employee ID", "First name", "Last name", "Salary", "Employee Type"
And I'm using something like this to call them inside 'Employee':
public int getEmployeeID() {
return EmployeeID;
}
But how can I get Employee Type? (BackEndDev,FrontEndDev,Intern)
Upvotes: 0
Views: 97
Reputation: 109
I'll answer your question with a question, why do you need a different object for each different employee type? The question you should ask yourself when creating a subclass is what extra functionality am I going to give this new object (Remember inheritance is when you want to provide a specialization for an object, https://docs.oracle.com/javase/tutorial/java/IandI/subclasses.html). Could what you are trying to do not be achieved by setting a property on the Employee object instead, perhaps an Enum for EmployeeType?
Employee.add(new Employee(100, "Emmanuel", "Santana", EmployeeType.BackEndDeveloper));
you could then access it via a getter, the same way you do for id?
Whilst getClass() would technically work for the scenario provided, is the overhead of creating and maintaining extra classes worth it every time you want to add a new type of employee? As well as the risks if you wanted to change the class name but something in your implementation was dependent upon it etc.
Upvotes: 1
Reputation: 909
If your aim is only to display Employee
informations, you can simply override toString()
method.
This way, every objects are capable of building a string of its own information; like this:
public class Intern {
// Fields, constructors and methods omitted
public String toString() {
return this.id + ", " + this.firstname + ", " + this.lastname + ", Intern";
}
}
Upvotes: -1
Reputation: 18309
You can simply use getClass():
BackEndDeveloper dev = new BackEndDeveloper(100, "Emmanuel", "Santana");
System.out.println(dev.getClass()); //print packageName.BackEndDeveloper
Note: If you just want BackEndDeveloper
, you can use getClass().getSimpleName()
.
System.out.println(dev.getClass().getSimpleName()); //print BackEndDeveloper
Upvotes: 1
Reputation: 2602
To get back the type you can call the getClass()
List<Employee> employees;
for(Employee e : employees){
System.out.println(e.getClass()); //will print Backend/Frontend depending on what type it is
}
Upvotes: 0