Search This Blog

Wednesday, August 4, 2010

Java : using polymorphism

Case :-  A simplepaint application is needed to be make in Java. The editor should have the following features
  • Buttons to draw shapes like circle , rectangle 
  • A brush icon which clicked opens a color box ..After choosing the color  , the user should be able to click  it to the any of the shapes and the color should be filled. 
 For starters let us take this as a simple case.
What would be a good java design for this task . ?

Lets take a solution and see how good it is ..

Class Circle
{
   drawCircle();
    fillColor() ;
}
Class Rectangle
{

   drawRectangle();
    fillColor() ;

}


Now we could have  some events based upon the click. if the user clicks upon circle shape..

(for circle)
onClick =  new Cirlce().drawCirlc();
 (for rectangle)
onClick =  new Rectangle().drawRectangle();
Looks good .

What about filling the color ??

 let say the user has drawn five differnt shapes. so we have five different objects of various classes (Circle , Rectangle )
So we first have to identify which object was clicked, then based upon that we call the corresponding method

 if(it is of object-1)
  object-1.fillColor();
else if (it is of object-2)
  object-2.filColor();

So on.....
Clearly this is not a good design .  The problem with this is design is that we are not using the fact that there is a abstraction . There is a common property that every shape posses. Each shape circle , rectangle , hexagon is different form of a general abstraction called (shape) . Here is when we introduce ploymorphism.
Ploymorphism is defined as having many forms . Java uses this concept very widely .
 you should know the concept of Inheritence before reading further .
A better design

abstract Class Shape
{
  
   abstract  void   draw();

   abstract  void  fillColor() ;
  //other common properties
}

Class Circle extends Shape
{
  // circle specific 


     void draw(){
   //implement draw for circle 
    }

   void fillColor(){
   //implement fillColor for circle 

    }
}
//Similarly
Class Rectagle extends Shape{

}

Now I am leaving it to the reader to figure out why this design is better.  It is more fun that way .I also encourage enthust Java developer to post their suggestions . If you have some other scenerio where you need help in designing , please feel free to email me at goyalsanyam[aat] gmail [ddot] com