繁体   English   中英

我可以将方法参数键入“此类”吗?

[英]Can I have a method argument typed “this class”?

我希望在接口的方法签名中有一个类型为“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){
        ...
    }
}
这是可能的,还是我应该将参数与接口绑定并让每个实现检查它?

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

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

public interface MyInterface<T extends MyInterface<T>> {
   public T myMethod(T other);
   ...
}

暂无
暂无

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

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