6 ms·
You're mistaken. Animal animal = zoo.getAnimal(); Can I do animal.bark() or animal.fly() ? All I know is that it's an Animal of some sort, may or may not be a
by ighost 17y ago
You're mistaken.
Animal animal = zoo.getAnimal();
Can I do animal.bark() or animal.fly() ? All I know is that it's an Animal of some sort, may or may not be an instance of the Dog or Bird subclasses of Animal.
- pvg 17y agoThis kind of synthetic example is silly, though. The fundamental questions would be the same in Python as well. How did you end up with this heterogeneous collection of objects? Why are you unable to get a collection of objects that are known to support your desired protocol at that point? What happens if they don't? Etc, etc, etc. You might make very different design choices in a statically or dynamically typed language but thinking about zoos and animals with no context isn't particularly informative.
- ighost 17y agoSynthetic? Yes. Contrived? No. I've seen this sort of thing in my own and other people's Java code, where you know what class it is but not the most-derived subclass. That's how polymorphism happens.
- pvg 17y agoRight. It doesn't happen by rooting around objects looking for methods by name. That's usually a sign of some misdesign that's making you re-invent the polymorphic mechanisms of the language yourself. True both in Java and Python.
- ighost 17y agoI agree that polymorphism is the "right way" if there's already a class hierarchy established. If the superclass-subclass relationships aren't in place for you (worse yet, they're not set up how you want them to be set up), this hack accomplishes a similar effect with no refactoring.
- statictype 17y agoWe're swaying off topic here, but, would animal.bark() or animal.fly() even compile under the Java compiler? Unless the Animal type responds to fly and bark (unlikely in this scenario) that looks like a compile error to me.