简体   繁体   中英

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

I want to have an argument of type "this class" in an interface's method signature, so that any class, for example MyClass , implementing it will have that method with an argument of 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){
        ...
    }
}
Is this possible, or should I just bind the argument with the interface and have each implementation check for it?

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

This somewhat enforces that T is the class that implements the interface:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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