I want to make an interface that forces each class that implements it to have a certain functionality, for the implemented class’ type.
So say I have classes MyClassA, MyClassB, MyClassC, etc. that all need a function on their own type:
in MyClassA:
public class MyClassA implements MyClass {
MyClassA function(MyClassA x) {
doSomethingImplementedInMyClassA(x);
}
}
in MyClassB:
public class MyClassB implements MyClass {
MyClassB function(MyClassB x) {
doSomethingImplementedInMyClassB(x);
}
}
The question is, how to write the interface MyClass to require such function?
public interface MyClass {
MyClass function(MyClass x);
}
obviously doesn’t work, since the returning type is MyClass and not its implementation. How to do this properly in Java?
You can use generics:
This is called the CRTP.
This is not perfect; it would still allow things like
To do this correctly, you need higher-kinded types [citation needed], which Java does not support.