实现同一接口的两个类能否在其公共方法中使用另一个类的对象作为参数?
在甲骨文文档interfaces中有一个非常令人困惑的句子
If you make a point of implementing
Relatable
in a wide variety of classes, the objects instantiated from any of those classes can be compared with thefindLargerThan()
method—provided that both objects are of the same class.
我不确定我是否理解这一点
假设有一个类A
和B
实现接口Relatable
,我在main()
中有一个代码,如下所示
A a = new A();
B b = new B();
System.out.println(a.isLargerThan(b));
假设isLargerThan()
方法根据接口返回一个int
,以便打印工作
上述代码是否适用于任何A类和B类?我认为这是不可能的,因为每个类都有不同的实现,而且很可能是由于在各个类中
isLargerThan()
的实现中对类的类型进行了强制转换如果我的上述推断是正确的,那么oracle文档中强调any的原因是什么?这是我困惑的根源
我知道我应该实现它,看看它是否有效,但由于我是Java的初学者,我的实现本身可能会使它不起作用。这就是为什么我在这里问这个问题
# 1 楼答案
a.isLargerThan(b)
是否适用于类A
和B
完全取决于A
内的实现,该实现可能尝试将其参数强制转换为A
文档中强调的any用于指出
findLargest
方法可以应用于实现Relatable
的类的任何实例。但是,它还假设任何实现类中的isLargerThan
实现总是将参数强制转换为实现类在这种假设下,您可以使用
findLargest
来比较一个A
与另一个A
或一个B
与另一个B
,但不能使用A
与B
进行比较# 2 楼答案
如果您的接口方法签名为:
不应该出现问题
一切都取决于执行情况
如果A和B的实现可以与接口
Relatable
一起工作,则不会将其强制转换为特定的实现,也不会使用每个实现的特定属性-一切都必须正常# 3 楼答案
参数可以是接口。然后可以使用实现该接口的任何类
可比较的和比较的,值得一看
# 4 楼答案
是的,它可以适用于任何A和B(实现了Relatable),但需要注意的是,当A实现的值大于A时,它必须知道类型,从而知道比较的基础
例如,假设A是类卡车,B是类汽车,A和B都实现了可关联性
当比较一辆卡车和另一辆卡车时,我们希望比较的基础是载重能力。然而,当与汽车进行比较时,我们希望它能根据马力进行比较
因此,A的Islarger方法可以是:
因此,对“any”的强调如链接的最后一段所述:“这些方法适用于任何“relatable”对象,无论它们的类继承是什么。”
现在,Relatable只是一个演示接口的虚构示例。Java确实有一个名为“Comparable”的接口,值得一看——例如Why should a Java class implement comparable?