在 interfaces 上的 Oracle 文档中有一个很迷惑的句子
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
实现接口(interface) Relatable
并且我在 main()
如下。
A a = new A();
B b = new B();
System.out.println(a.isLargerThan(b));
假设 isLargerThan()
方法根据接口(interface)返回一个 int
以便打印工作。
以上代码是否适用于任何 A 类和 B 类?我认为这不应该是可能的,因为每个类都有不同的实现,并且很可能是由于在各个类中
isLargerThan()
的实现中转换为类的类型。如果我的上述推论是正确的,那么 oracle 文档中强调 any 的原因是什么?这是我困惑的根源。
我知道我应该实现它以查明它是否有效,但由于我是 Java 的初学者,我的实现本身可能会使其无效。这就是我在这里问的原因。
最佳答案
是的,它适用于任何 A 和 B(实现 Relatable),但需要注意的是,当 A 实现 isLargerThan 时,它必须知道类型 - 以及比较的基础。
例如,假设 A 是 Truck 类,B 是 Car 类,并且 A 和 B 都实现了 Relatable。
将一辆卡车与另一辆卡车进行比较时,我们希望比较的基础是负载能力。但是,在与汽车进行比较时,我们希望它根据马力进行比较。
所以,A 的 isLargerThan 方法可能是这样的:
public class Truck implements Relatable {
private int capacity;
private int horsepower;
public int isLargerThan(Relatable other) {
if (other instanceof Truck) {
Truck otherTruck = (Truck)other;
return Integer.signum(capacity - otherTruck.capacity);
} else if (other instanceof Car) {
Car otherCar = (Car)other;
return Integer.signum(horsepower - otherCar.getHorsepower());
} else {
// Maybe throw exception
}
}
所以对“任何”的强调如您链接的最后一段所述:“这些方法适用于任何“相关”对象,无论它们的类继承是什么。”。
现在,Relatable 只是一个演示接口(interface)的虚构示例。 Java 确实有一个名为“Comparable”的接口(interface),值得一试——参见示例 Why should a Java class implement comparable?
关于java - 实现相同接口(interface)的两个类可以在其公共(public)方法中使用其他类的对象作为参数吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19476062/