Aaa
Aaa

Reputation: 88

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?

Upvotes: 4

Views: 132

Answers (2)

Mark Cidade
Mark Cidade

Reputation: 99957

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

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

Upvotes: 3

Aaron Novstrup
Aaron Novstrup

Reputation: 21017

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

Upvotes: 3

Related Questions