• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Polymorphism help

 
Brian Jeling
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.

Thank You.



 
paul wheaton
Trailboss
Pie
Posts: 21665
Firefox Browser IntelliJ IDE Java
 
Campbell Ritchie
Sheriff
Pie
Posts: 49808
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Welcome to the Ranch

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.
 
fred rosenberger
lowercase baba
Bartender
Posts: 12186
34
Chrome Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Brian Jeling
Greenhorn
Posts: 3
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
@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.
 
Campbell Ritchie
Sheriff
Pie
Posts: 49808
69
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You're welcome
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic