Java Polymorphism - Selecting correct method based on subtype
Posted
by Marty Pitt
on Stack Overflow
See other posts from Stack Overflow
or by Marty Pitt
Published on 2010-05-20T18:00:12Z
Indexed on
2010/05/20
18:10 UTC
Read the original article
Hit count: 350
Hi
Given the following Class and Service layer signatures:
public class PersonActionRequest {
PersonVO person
// ... other fields
}
public class MyServiceLayerClass {
public void requestAction(PersonActionRequest request)
{
PersonVO abstractPerson = request.getPerson();
// call appropriate executeAction method based on subclass of PersonVO
}
private void executeAction(PersonVO person) {}
private void executeAction(EmployeeVO employee) {}
private void executeAction(ManagerVO manager) {}
private void executeAction(UnicornWranglerVO unicornWrangler) {}
}
As discussed here, java will select the best method based on type info at compile time. (Ie., it will always select executeAction(PersonVO person)
).
What's the most appropriate way to select the correct method?
The internet tells me that using instanceof
gets me slapped. However, I don't see the appropraite way to select the method without explictly casting abstractPerson
to one of the other concrete types.
Thanks
Marty
© Stack Overflow or respective owner