Polymorphism Please respond to the following Discuss a realw
\"Polymorphism\" Please respond to the following: Discuss a real-world example of how polymorphism might be used in a system you are familiar with.
Solution
Making of shapes.
Lets say you want to draw 5 shapes and for drawing the shape you have one function draw.
One way of doing that is create an object for each class and call the draw function.
Example:
Rectangle r;
r.draw();
Circle c;
c.draw();
Sqaure s;
s.draw();
Rhombus r;
r.draw;
etcetra
But this code become unmaintainable when you want to add 100 more shapes to your code and drawing each shape will result in cumbersome code.
To make this maintainable code we can make use of polymorphism.
As all the shapes have two things in common All of the objects represent one thing shape and have one function draw().If we make Shape as an abstract class and have a abstract draw function then all the shapes need to extend this class and need to implement this function.
Code,
abstract class Shape{
public abstract void draw();
}
Example of one class:
class Circle{
public void draw()
{
System.out.println(\"Drawing Circle\");
}
}
Now, to draw the shape all you have to do is to create the array of shapes since all the shapes extends from Shape class all the concrete objects can be assingned to an array of Shape objects.
Shape s[2] = {r,c};
You can use for loop to iterate the array and use s.draw() statement to draw all the shapes

