4 ms·
I think GP is talking about something like this: Fruit* fruit = new Apple(); ConsumeApple(fruit); // Doesn't work; requires Apple* fruit = new Ba
by cornstalks 3y ago
I think GP is talking about something like this:
Fruit* fruit = new Apple();
ConsumeApple(fruit); // Doesn't work; requires Apple*
fruit = new Banana();
ConsumeBanana(fruit); // Doesn't work; requires Banana*
ConsumeFruit(fruit); // Okay, function signature is void(Fruit*)
- sfn42 3y agoBut why would you want to be able to pass an apple to a function expecting a banana? Doesn't even make sense, the whole point is that the type system forces you to consider this stuff. If OP wanted to be allowed to do whatever and just have the software fail at runtime, JS is right there.
- mrkeen 3y ago> But why would you want to be able to pass an apple to a function expecting a banana? I would never. I know that I'm holding a banana, I want to pass it to a method that receives a banana. But what I can't do is put my banana through a rotateFruit function first, because then Java will forget that it's a banana and start treating it as a fruit.
- kaba0 3y agoJava has generic functions since forever, something like `<T extends Fruit> T rotateFruit(T fruit)` would return your banana typed object just fine.
- skydhash 3y agoInheritance is just a tool, that you use if it fits you software architecture. You use other tools, like generics, interface, where it makes senses to ise them. I think people wants the one true way to not have to design their software. And when they use inheritance in a ways that does not fit, they blame inheritance.
- mrkeen 3y agoBut then I lose polymorphic dispatch, which is where this thread started.
- kaba0 3y agoIf you pass your object to another function, you only get static dispatch. What you want instead in this case, is a simple instance method. Then yourApple.rotateFruit() would do what you want, and rutateFruit could be an interface method declared in Apple, the superclass/interface.