4

我想在接口的方法签名中有一个“this class”类型的参数,以便任何实现它的类(例如MyClass,实现它的类)都有一个带有 type 参数的方法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){
        ...
    }
}
这可能吗,还是我应该将参数与接口绑定并让每个实现检查它?

4

2 回答 2

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){
      ...
   } 
}
于 2010-08-28T02:59:12.120 回答
3

这有点强制 T 是实现接口的类:

public interface MyInterface<T extends MyInterface<T>> {
   public T myMethod(T other);
   ...
}
于 2010-08-28T03:18:21.867 回答