I think the following cannot be done in Java. But I would be happy to know how to implement something similar to it.
Suppose we have a class C that is already used in compiled code. (We can neither modify this code nor the original definition of C).
Suppose further that there is interesting code that can be reused if only C implements interface I. In fact, it is more or less trivial to output D, and this is just a C + implementation of the interface methods.
However, it seems that there is no way, as soon as I have C, to say: I want you to be D, that is, C implementing I.
(Side note: I think that casting (D) c, where c is the run-time type of C, should be allowed if D is C, and only the difference with C. are the added methods. This should be safe if it not this way? )
How can this disaster be circumvented?
(I know the factory design pattern, but this is not a solution. It seems that if we manage to create D in all places where C used to be, someone else found another interface J useful and got E extends C implements J. But E and D incompatible, because they both add a different set of methods to C. Therefore, although we can always pass E where C is expected, we cannot pass E where D is expected Rather, now we need a new class F extends C implements I, J.)
source
share