Mark As Completed Discussion

The Polymorphism Way

The implementation above has several drawbacks. What if we wanted to do some other operations on the user's given shapes? We would have to do that operation on each object in each case block. What if you had hundreds of different shapes? You would need to update hundreds of blocks just to add a similar-looking line! We would also need more ArrayLists to hold the results.

Polymorphism to the rescue! Let's re-implement this program using the concept of polymorphism. We know that all rectangles, circles, and squares are a type of Shape, so we can declare all of these as shapes and use a common rule for them. We will do the following things in our code:

  1. Create a shapeClasses array where all the blueprints (class references like Rectangle, Square, etc.) will be kept.
  2. When a user gives inputs to create an ith shape, we will automatically create an instance of that class from the shapeClasses array.
    • Note that we create the (i-1)th shape according to the user input i since arrays are 0 indexed.
JAVA
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

javascript

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

python

PYTHON
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

cpp

CPP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

csharp

CSHARP
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

go

GO
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment