Nov
2012
A short Java puzzle
In what follows, a short Java puzzle will be stated and solved for the reader. Neither the statement, nor the solution belong to me, but to the technical environment I work in.
We are given a standalone interface (one which doesn’t have an ancestor). The interface contains two method declarations. Next, we are given a concrete class (having no other ancestor except Object) that fully implements this interface. The class, however, contains only one method.
Is this scenario possible? If yes, how?
The solution is based on using a generic in the interface declaration. The generic must not induce the same erasure to the two methods, because, in this case, by having duplicated a method signature we will get a compiler error. We declare two methods, having the same return type, the same name, and the same number of arguments (1). The first method will have a parameter of the generic type (at runtime this will be an Object), while the second method will have a parameter of an arbitrary type (say String). The class will implement the interface with the generic bound to the argument type of the second method (String). The two method signatures will overlap, leading to just one method in the class.
interface MyInterface<T> {
void myMethod(T t);
void myMethod(String t);
}
class MyClass implements MyInterface<String> {
@Override
void myMethod(String t) {}
}