【问题标题】:java interface method input itselfjava接口方法输入本身
【发布时间】:2018-02-07 19:50:33
【问题描述】:

我有一个接口,该接口有一个自身的方法,例如

public interface Vehicle {
  void bump(Vehicle other);
}

现在,我想实现这个接口,使 Vehicle 只会撞到它自己类型的 Vehicles。也就是说,我想要诸如

之类的东西
public class BumperCar implements Vehicle {
  public void bump(BumperCar other){
    System.out.println("They bounce off harmlessly and continue going.")
  }
}

public class Train implements Vehicle {
  public void bump(Train other){
    System.out.println("Breaking news: Dozens die in horrible train on train collision.")
  }
}

但是 BumperCars 和 Trains 之间的颠簸没有任何作用,即使两个类都必须实现颠簸(Vehicle)。实现这一目标的最佳方法是什么?

【问题讨论】:

  • 您没有覆盖该方法。它有不同的签名。
  • 您是否希望不同类型的车辆相互碰撞。?此外,在实际使它们碰撞的地方添加代码。

标签: java methods types parameters interface


【解决方案1】:

由于 Java 无法在类中使用 self 类型,因此通常使用称为“模拟自身类型”的通用构造:

abstract class Vehicle<T extends Vehicle<T>> {
    public abstract void bump(T other);
}

public class Car extends Vehicle<Car> {
        @Override public void bump(Car other) {}
}

唯一需要注意的是,必须始终在类声明中指定类型。

在核心 Java 库中,模拟 self-type 用法的一个示例是 Enum 类。

【讨论】:

  • 这是一个很好的答案,我可能会在我对代码及其使用方式控制较少的环境中使用它,因为这会更好地强制类型。但由于这是我的代码,而且我更愿意传递正确的类型,所以我将使用 Lars 的答案。
【解决方案2】:

你需要使用自引用泛型类型:

    public interface Vehicle< T extends Vehicle<T> > {
        void bump(T other);
    }

    public class BumperCar implements Vehicle<BumperCar> {

        public void bump(BumperCar other){
        }
   }

    public class Train  implements Vehicle<Train > {

        public void bump(Train  other){
        }
   }

【讨论】:

    【解决方案3】:

    我对“可能重复的评论”中提到的解决方案不太满意,所以我将展示我将如何做到这一点。

    首先,正如我在评论中所说,您没有从接口覆盖方法。签名需要匹配。

    为了做到这一点,请使用接口中的签名创建一个函数。并且在该方法中使用instanceof 运算符来检查您的对象是否来自正确的类型。像这样:

    public class BumperCar implements Vehicle {
      public void bump(Vehicle other){
        if(other instanceof BumperCar) {
            System.out.println("...");
        }
      }
    }
    

    【讨论】:

    • 我同意,我对这些答案不满意。这就是我要做的方式。谢谢!
    猜你喜欢
    • 2018-07-09
    • 1970-01-01
    • 2012-05-22
    • 1970-01-01
    • 2022-10-19
    • 2013-06-21
    • 1970-01-01
    • 2019-02-10
    • 2014-07-17
    相关资源
    最近更新 更多