• Post Reply Bookmark Topic Watch Topic
  • New Topic

why and when to use polymorphism  RSS feed

 
subhit chauhan
Ranch Hand
Posts: 40
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I know the defination of polymorphism, but dont know when and why we need to use polymorphism. Many books tells about it but never said WHY one should use it and when!
can't get it, why to use polymorphism, what is the benefit? Trade off?
 
eammon bannon
Ranch Hand
Posts: 140
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

why to use polymorphism, what is the benefit?

You are programming in Java? Then its not a choice, you can't avoid using polymorphism.
The biggest benefit of polymorphism is that it allows for extensible programs. You can have an API which deals with base types, and requires no knowledge at the time of writing what extra types might be required in the future. But because the API uses polymorphism it means if I create a new class by extending an existing one or implementing an existing interface I know that my new object will work seemlesly with the existing API.
It also means I can keep things general in my code. If I have a method that handles circle objects and square objects, it makes sense to define a base class or an interface "shape" and write methods to this base class or interface. Then I'm using the polymorphic nature of java to decide at run time which object I'm dealing with. So for example without polymorphism, I would need to write a methods to handle circles and methods to handle squares. And if I added a new triangle object I would have to rewrite existing code to handle this. But with polymorphism, I don't have these worries - my API just handles shapes, and all my object are of the type shape. Nice and easy.
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can discover the need for inheritance a couple ways. If you have several classes that seem to be doing the same thing a lot, you can "generalize" those duplicate methods into a new base class. Then your other classes can inherit the behavior. Or you can find that a class does some things (but not all things) differently under different conditions and "specialize" the behavior into multiple derived classes. I like those verbs to help you analyze why you think you need use inheritance - generalize & specialize.
Either way, inheritance is a very strong form of coupling. That is, the extended class has a strong dependency on the base class. Changes in the base class can break the extended class. Strong coupling is something we usually avoid, so keep an eye out for inappropriate or excessive inheritance. Here's an article called
Extends Is Evil. That's an obvious exaggeration, but it's still an interesting point of view.
You asked about polymorhpism rather than inheritance, and there is another way to get polymorphism - through Interfaces. Interfaces generally avoid the risks that the article talks about. Learn to love em. They are key to the more advanced OO principles and patterns.
 
sever oon
Ranch Hand
Posts: 268
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I just used a "pure" example of polymorphism at work the other day. We are using a mysql database and we have to use SQL that's specific to that DB. So we're using the popular DAO pattern (Data Access Object) where info from the DB is only exposed to the application through DAOs that encapsulate all of the SQL and DB handling.
mysql has an SQL feature that allows you to specify a limit and an offset of a dataset. For instance, if I run an SQL query that returns the numbers 1 through 10, and then I rerun that query with a limit of 5, it'll only return 1 through 5. If I rerun the same limited query with an offset of 5, it'll return 6 through 10. This is for paginating over large datasets (javaranch probably uses it to split up long threads into pages).
So when you ask the DAO for data you have to specify the conditions of the query, limit and offset being one of them. We call these filters. When you pass a filter into a particular method on a DAO to do a particular query, it builds the SQL statement by doing some specific stuff and some general stuff--for instance, adding the limit and offset to the end of an SQL statement is the same bit no matter what query you're running, so you pass your filter to a common method that appends it to your SQL StringBuffer.
How does this method take any filter, get the limit and offset info and append it? You'd have to have a method for every type of data filter in the system if not for polymorphism.
Instead, you can create a bunch of interfaces for your filters, and if your particular filter wants to support that functionality and allow limits and offsets, for instance, you simply implement the PagableFilter interface (with getLimit() and getOffset()). Now, you can write a common method that takes a PagableFilter, calls those methods, constructs the bit of SQL and appends it to the StringBuffer you hand in.
Polymorphism at work. A bit long-winded, but worth it to show a 100% real-world example.
sev
 
Thomas Paul
mister krabs
Ranch Hand
Posts: 13974
  • Likes 1
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Suppose you work for a company that sells books. So you make a very nice class called "Book" that handles everything that you need to know about a book. You write all sorts of classes for billing, shipping, creating invoices, all using the Book class. One day your boss comes in and says, "Great news! The company is expanding and we are selling CD's now!" Not great news because now you have to change every class that uses Book to also use CD. But what if you had originally created an interface (or an abstract class) called "ThingWeSell", and Book implemented this interface. Then you could have written all your shipping, invoicing, etc classes to use that interface instead of Book. Now all you would have to do is create a new class called CompactDisc which implements the ThingWeSell interface. Because of polymorphism, all of the other classes could continue to work without change!
 
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!