You can use double call. No promises is the best solution, but it is an alternative.
Code example
import java.util.HashMap; public class Example { public static void main(String[] argv) { Example ex = new Example(); ICacheable[] cacheableObjects = new ICacheable[]{new MyObject(), new OtherObject()}; for (ICacheable iCacheable : cacheableObjects) {
The idea here is that instead of casting or using instanceof you call the iCacheable object .put(...) method, which returns to the overloaded methods of the Example object. Which method is called depends on the type of this object.
See also visitor template . My code sample smells because the ICacheable.put(...) method is incompatible - but using the interfaces defined in the Visitor template can clear this smell.
Why can't I just call this.put(iCacheable) from the Example class?
In Java, redefinition is always bound at run time, but overloading is a bit more complicated: dynamic dispatch means that the implementation of the method will be selected at run time, but the signature of the method is nevertheless determined at compile time. (Refer to the Java Language Specification, chapter 8.4.9 for more information, and see the βMaking Hash of Itβ puzzle on page 137 of the Java Puzzlers book.)
source share