Win a copy of Kotlin in Action this week in the Kotlin forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Question on polymorphism from JavaRanch Campfire story  RSS feed

 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I read the following JavaRanch Campfire story on polymorphism

javaranch campfire



So why not just use a generic collection like Vector? Can't you just put any object in there -- they don't even have to be from the same inheritance tree.

You've missed the point. A Vector would be less efficient, for one thing, and you'd have to cast the objects back to something more specific before you could call methods (other than, say, toString()).

What a pain. And that's not the main problem.

What if another programmer comes along after the guy who wrote the Animal program is gone? What if you don't even have his source code, but you need to add a new animal subclass like Cow? If all the different Animal subclasses had to be figured out, and cast, etc. then you could not add new Cow animals into the program without changing the original code.

But if the Animal program is simply expecting an array of Animals, then all I have to do is make my new Cow class a subclass of Animal, then it can be safely included in an Animal [] array and passed to a method in the Animal program.


I was not able to understand the problem highlighted in here about using the Vector and its related casting issue.
Also the subsequent problem about not being able to add new subclass "Cow" if a Vector was used in
place of Animal[] array
 
Campbell Ritchie
Marshal
Posts: 55717
163
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Try thisYou might have to write a bit more code to get it to work properly
 
Rajiv Rai
Ranch Hand
Posts: 57
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Any more examples with sample code on why is it not
advisable to use Vector rather than an Animal array..


Thanks
 
Winston Gutkowski
Bartender
Posts: 10573
65
Eclipse IDE Hibernate Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Rajiv Rai wrote:Any more examples with sample code on why is it not
advisable to use Vector rather than an Animal array..

Not really. Vector is a legacy class from the time when Java was very new, and it's been superceded by better and faster ones since then (notably ArrayList). The same is true of Enumeration, StringTokenizer and several others.

Basic rule: If you find them in old code: leave them (unless you fancy a refactoring exercise). If you're writing new code: don't use them.

Winston
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!