Reputation: 7714
I have two classes implementing an interface :
public interface Vehicle {…}
public class Car implements Vehicle {…}
public class Shoes implements Vehicle {…}
At the user level I am dealing with the interface, and functions are usually of the form function(Vehicle v)
:
public class Controller {
@Inject
Service service;
public int get(Vehicle v) {
return service.getShortestPathLength(v);
}
}
However at some point I have a method which I want to be able to discriminate between the implementations, because the operations on this particular part are very different (e.g. in my example sample the paths by foot, by car, by plane or by boat would be completely different). That is, I would like getShortestPathLength(v)
to switch automatically (i.e. without explicit if
testing) to the correct overloaded method depending on the implementation of v
:
public class Service {
public int getShortestPathLength(Car c) {…}
public int getShortestPathLength(Shoes s) {…}
}
However it doesn’t seem to work as is, I get an Unresolved compilation problem error :
The method
getShortestPathLength(Vehicle)
in the typeService
is not applicable for the arguments(Car)
Is what I am trying to achieve possible, and if so what am I missing ?
My current workaround is to test v.getClass().getSimpleName()
within getShortestPathLength(Vehicle v)
, but although it works it doesn’t seem quite an optimized use of object-oriented programming.
FWIW I’m running Java 11 with Quarkus 1.6.0.
Upvotes: 0
Views: 627
Reputation: 388
I can suggest three options:
Your workaround is not bad, but I do not think checking type of entities in run time is good idea.
Upvotes: 1