有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

实现同一接口的两个类能否在其公共方法中使用另一个类的对象作为参数?

在甲骨文文档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 the findLargerThan() method—provided that both objects are of the same class.

我不确定我是否理解这一点

假设有一个类AB实现接口Relatable,我在main()中有一个代码,如下所示

A a = new A();
B b = new B();

System.out.println(a.isLargerThan(b));

假设isLargerThan()方法根据接口返回一个int,以便打印工作

  • 上述代码是否适用于任何A类和B类?我认为这是不可能的,因为每个类都有不同的实现,而且很可能是由于在各个类中isLargerThan()的实现中对类的类型进行了强制转换

  • 如果我的上述推断是正确的,那么oracle文档中强调any的原因是什么?这是我困惑的根源

我知道我应该实现它,看看它是否有效,但由于我是Java的初学者,我的实现本身可能会使它不起作用。这就是为什么我在这里问这个问题


共 (4) 个答案

  1. # 1 楼答案

    a.isLargerThan(b)是否适用于类AB完全取决于A内的实现,该实现可能尝试将其参数强制转换为A

    文档中强调的any用于指出findLargest方法可以应用于实现Relatable的类的任何实例。但是,它还假设任何实现类中的isLargerThan实现总是将参数强制转换为实现类

    在这种假设下,您可以使用findLargest来比较一个A与另一个A或一个B与另一个B,但不能使用AB进行比较

  2. # 2 楼答案

    如果您的接口方法签名为:

    int isLargerThan(Relatable r);
    

    不应该出现问题

    一切都取决于执行情况

    如果A和B的实现可以与接口Relatable一起工作,则不会将其强制转换为特定的实现,也不会使用每个实现的特定属性-一切都必须正常

  3. # 3 楼答案

    参数可以是接口。然后可以使用实现该接口的任何类

    可比较的和比较的,值得一看

  4. # 4 楼答案

    是的,它可以适用于任何A和B(实现了Relatable),但需要注意的是,当A实现的值大于A时,它必须知道类型,从而知道比较的基础

    例如,假设A是类卡车,B是类汽车,A和B都实现了可关联性

    当比较一辆卡车和另一辆卡车时,我们希望比较的基础是载重能力。然而,当与汽车进行比较时,我们希望它能根据马力进行比较

    因此,A的Islarger方法可以是:

    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
            }
        }
    

    因此,对“any”的强调如链接的最后一段所述:“这些方法适用于任何“relatable”对象,无论它们的类继承是什么。”

    现在,Relatable只是一个演示接口的虚构示例。Java确实有一个名为“Comparable”的接口,值得一看——例如Why should a Java class implement comparable?