Consider I have the following interface:
public interface A { public void b(); }
However I want each of the classes that implement it to have a different return type for the method b().
Examples:
public class C {
public C b() {}
}
public class D {
public D b() {}
}
How would I define my interface so that this was possible?
If the return type must be the type of the class that implements the interface, then what you want is called an F-bounded type:
In words,
Ais declaring a type parameterTthat will take on the value of each concrete type that implementsA. This is typically used to declare things likeclone()orcopy()methods that are well-typed. As another example, it’s used byjava.lang.Enumto declare that each enum’s inheritedcompareTo(E)method applies only to other enums of that particular type.If you use this pattern often enough, you’ll run into scenarios where you need
thisto be of typeT. At first glance it might seem obvious that it is1, but you’ll actually need to declare anabstract T getThis()method which implementers will have to trivially implement asreturn this.[1] As commenters have pointed out, it is possible to do something sneaky like
X implements A<Y>ifXandYcooperate properly. The presence of aT getThis()method makes it even clearer thatXis circumventing the intentions of the author of theAinterface.