Skippy le Grand Gourou
Skippy le Grand Gourou

Reputation: 7714

Can method overloading discriminate automatically between an interface implementations?

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 type Service 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

Answers (1)

Chi Cuong Le
Chi Cuong Le

Reputation: 388

I can suggest three options:

  • Move getShortestPathLength() to Verhicle, and implement differently depends on individual charaters of Car and Shoes. This option increases encapsulation. If this option can be implemented depends on your logic. In case getShorttestPathLength can be implemented using data in Verhicle, no other information required
  • Declare 3 different functions using overloading technique in Service, and divide your code in Service implementation to small meaningful block to get them reused in different functions. By using this option, we have to give correct type of parameter for each call, in order to get correct method to be loaded.
  • Declare an interface of Service with one method: getShortesPathLength. Implement different variants for Service with different logic. Inject correctly instances of Service so that correct implementation can be called. This option based on polymorphism of Service

Your workaround is not bad, but I do not think checking type of entities in run time is good idea.

Upvotes: 1

Related Questions