Hello my name is Brian. I am learning polymorphism at the moment but still unclear of the concept.
I'm having some problems figuring out what would be that advantage of using a superclass reference pointing to a subclass.
I took this snippet from the Sun Certified Java Programmer book.
The part I dont understand is why do we need to do: Animal b = new Horse() when we can easily do Horse b = new Horse() to get a Horse object?
I also looked on the JAVA API as instructed but I still have some doubts.
You can create a reference which is called by a particular type. Then you can make that reference point to an object of that type or any of its subclasses. If you create a reference to Animal, then all its instance methods are available. If, for example, the Horse class has a buck() method, that might not be available in Animal, so you cannot call it on an Animal reference. You can, however, call the eat() method, which is in the Animal class (suggesting that all kinds of Animal eat, but only horses buck). When you call the eat() method on an Animal reference which points to a Horse object, you use run-time binding, which finds the versipon of that method in the actual object, so you will execute the Horse version.
Beware: don't try polymorphism on static methods. It doesn't work.
Sometimes, you don't know what you're going to get. Perhaps you have a collection of animals - like in a zoo. you want each animal to eat. so you write a loop (i'm using pseudo code, not actual java code)
This is much simpler and cleaner than
the REALLY cool thing is that the first way, the zookeeper can add new animals types whenever they want. You don't even have to know what it is, and you never have to touch that code. However, the second way, each time a new animal is added, you'll have to go back in and add another 'else-if' to your conditions.
Never ascribe to malice that which can be adequately explained by stupidity.
Joined: Oct 01, 2010
@paul wheaten - Thanks I've just read both links and it was great.
@Campbell Ritche - Thanks for the welcome and the explanation.
@fred rosenberger - Thanks for showing an example of the advantage and disadvantage of polymorphism.