我希望在接口的方法签名中有一个类型为“this class”的参数,因此任何实现它的类(例如MyClass
)都将使用类型为MyClass
的参数的方法
public interface MyInterface {
public thisClass myMethod(thisClass other);
...
}
public class MyClass implements MyInterface {
// has to reference this class in the implementation
public MyClass myMethod(MyClass other){
...
}
}
这是可能的,还是我应该将参数与接口绑定并让每个实现检查它?
答案 0 :(得分:3)
public interface MyInterface<T> {
public T myMethod(T other);
...
}
public class MyClass implements MyInterface<MyClass> {
// has to reference this class in the implementation
public MyClass myMethod(MyClass other){
...
}
}
答案 1 :(得分:3)
这有点强制T是实现接口的类:
public interface MyInterface<T extends MyInterface<T>> {
public T myMethod(T other);
...
}