4 ms·
I hadn't thought of interfaces (e.g. sortable) as being an OO thing. That said, I do sometimes confuse myself trying to use them in Java, e.g. void foo()
by mrkeen 6y ago
I hadn't thought of interfaces (e.g. sortable) as being an OO thing.
That said, I do sometimes confuse myself trying to use them in Java, e.g.
void foo() {
Fruit[] basket = new Apple[] { new Apple(), new Apple() };
handleFruit(basket[0]);
}
void handleFruit(Fruit fruit) {
System.out.println("Do I get called?";
}
void handleFruit(Apple apple) {
System.out.println("Or do I?";
}
If it were runtime polymorphism I'd expect it to dispatch to the apple method, but it dispatches to the fruit method.
I also run up against friction trying to define, e.g. the "mappable" interface across these two guys. Can't seem to get it done.
class Optional {
<U> Optional<U> map(Function<? super T,? extends U> mapper);
}
class Optional {
<R> Stream<R> map(Function<? super T,? extends R> mapper);
}
For what it's worth, Java went with the polymorphic Collections.sort(data) approach, not the polymorphic data.sort() approach.
- tpxl 6y ago>Collections.sort(data) approach, not the polymorphic data.sort() Since java 8, java.util.List had a sort method and Collections.sort(List) just calls List::sort. Before that, only the Collections.sort method existed. At least from java 6 on, java has a SortedSet and SortedMap that accept comparators as constructor parameters, but have no sort methods (So basically data.sort, not collections.sort(data)). Arrays can of course only be sorted via Arrays.sort, since arrays have no methods.
- _old_dude_ 6y agoJava like C++ or Swift uses single-dispatch polymorphism, so only the receiver (the argument before the '.') is used at runtime. In Java, you can implement your own dispatch table quite easily Map<Class<?>, Consumer<Fruit>> dispatchTable = Map.of(Apple.class, fruit -> handleFruit((Apple)fruit)); Fruit fruit = basket[0]; dispatchTable.get(fruit.getClass()).accept(fruit);
- pjmlp 6y agoIn C++ you can fake multi-dispatch, by making use of templates, templates specialization and overloading though. It is just somewhat cumbersome.