Some notes:
- Ignore the
getDeclaredConstructor
part for now. - We are instantiating an object from the class with the
newInstance
method instead of thenew
keyword. There are many more ways to instantiate an object. There are also several design patterns (e.g. Factory Design Pattern) to create objects. - Notice that we are putting all the subclasses of Shape (Rect, Circle, etc.) into the Shape type. This means that Rectangle, Circle, and Square act as Shape types which is an example of polymorphism.
- If a class in shapeClasses is not inherited from Shape, then the compiler will panic which is why we need a try-catch block.
Notice how much more concise the code becomes when compared to the previous one. Also, if we had to do some other stuff and call other methods, we can just add that command after the for
loop just like how we called the getArea()
method: writing it once and applying it to all shapes. This is the power of polymorphism. Later we will learn more about what polymorphism can do when we understand interfaces and adapters.