【发布时间】:2020-08-17 14:56:21
【问题描述】:
我有两个实现接口的类:
public interface Vehicle {…}
public class Car implements Vehicle {…}
public class Shoes implements Vehicle {…}
在用户层面我处理的是界面,函数通常是function(Vehicle v)的形式:
public class Controller {
@Inject
Service service;
public int get(Vehicle v) {
return service.getShortestPathLength(v);
}
}
但是在某些时候我有一个方法我希望能够区分实现,因为这个特定部分的操作非常不同(例如,在我的示例中,步行、汽车、飞机或乘船将完全不同)。也就是说,我希望getShortestPathLength(v) 根据v 的实现自动切换(即没有明确的if 测试)到正确的重载方法:
public class Service {
public int getShortestPathLength(Car c) {…}
public int getShortestPathLength(Shoes s) {…}
}
但它似乎没有按原样工作,我收到一个未解决的编译问题错误:
Service类型中的方法getShortestPathLength(Vehicle)不适用于参数(Car)
我正在努力实现的目标是否可行,如果可以,我错过了什么?
我目前的解决方法是在getShortestPathLength(Vehicle v) 中测试v.getClass().getSimpleName(),但尽管它有效,但似乎并不是对面向对象编程的优化使用。
FWIW 我正在使用 Quarkus 1.6.0 运行 Java 11。
【问题讨论】:
-
你在哪里声明 foobar 函数?在接口 I 中还是在其他类/接口中?
-
@ChiCuongLe
foobar在服务中声明并在控制器中调用。 -
您正在尝试以下内容:ServiceInterface -> foobar(I param)、ServiceImpl1 -> foobar(A param)、ServiceImpl2 -> foobar(B param)?在这种情况下,它不能工作,就像编译器抱怨:D。因为那不是方法重载,那是多态
-
我不确定,你能详细说明一下吗?请注意,接口和类是在它们自己的目录中定义的,而不是在服务中。
-
您的设计不适合 Java,如果您更详细地解释您的应用案例,我们可能会提供更好的建议。多态背后的一般概念是
foobar不应该关心I的实现,只关心合约,如果需要一些额外的细节,那么它应该是合约的一部分以某种方式。
标签: java oop interface parameter-passing overload-resolution