繁体   English   中英

java接口方法输入本身

[英]java interface method input itself

我有一个接口,该接口本身具有一种方法,例如

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

现在,我想以一种方式实现这个接口,使得Vehicle只会碰到自己类型的Vehicle。 也就是说,我想要一些诸如

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.")
  }
}

但是,即使两个类都必须实现umph(Vehicle),BumperCars和Trains之间的碰撞也不会起作用。 实现此目标的最佳方法是什么?

由于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库中, Enum类是模拟的自我类型用法的一个示例。

我对“可能重复的评论”中提到的解决方案不太满意,因此我将展示如何实现。

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

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM