views:

90

answers:

2

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?

+3  A: 
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){
      ...
   } 
}
Aaron Novstrup
Hmm. It looks pretty clunky, but it does exactly what I wanted. I'll probably end up using this, thanks.
High Five
public class Foo implements MyInterface<Bar> { public Bar myMethod(Bar other) { // this isn't what you want is it? }}
Ron
I will be writing any classes that implement this myself, so I'll make sure I don't do that. I wasn't looking for a way to enforce this, just wondering if it's doable without if checks in the method. (Though I guess in both cases it comes down to preconditions)
High Five
+3  A: 

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

public interface MyInterface<T extends MyInterface<T>> {
   public T myMethod(T other);
   ...
}
Mark Cidade
It does not. Consider (1) abstract class MyImpl1 implements MyInterface <MyImpl1> { }; (2) abstract class MyImpl2 implements MyInterface <MyImpl1> { }. The second does not do what High Five wants.
emory
I added a 'somewhat' qualifier. I think that it's as close as you can get to what High Five wants.
Mark Cidade
Once again, I will be writing these myself, so I don't need that bound, or encounter (2). I was just wondering if it's doable without if checks in the method.
High Five