簡體   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