Forums Register Login

Question on polymorphism from JavaRanch Campfire story

+Pie Number of slices to send: Send
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
+Pie Number of slices to send: Send
Try thisYou might have to write a bit more code to get it to work properly
+Pie Number of slices to send: Send
Any more examples with sample code on why is it not
advisable to use Vector rather than an Animal array..


Thanks
+Pie Number of slices to send: Send
 

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
That new kid is a freak. Show him this tiny ad:
a bit of art, as a gift, that will fit in a stocking
https://gardener-gift.com


reply
reply
This thread has been viewed 689 times.
Similar Threads
polymorphism
Inheritance and Polymorphism
Upcasting.....Its confusing
Switch statement vs Polymorphism
Can you do this with an ArrayList?
More...

All times above are in ranch (not your local) time.
The current ranch time is
Mar 28, 2024 14:28:32.