1068. Practice (Run Time Polymorphism)
Design a class hierarchy to calculate the area of different shapes using runtime polymorphism. Implement a base class Shape with a method getArea() that will be overridden in derived classes Circle and Rectangle. Demonstrate runtime polymorphism by using a driver class to calculate and display the area of objects of type Shape.
Base Class : Shape :
Method :
- getArea() : Returns a double value representing the area of the shape. Defined as virtual in C++ or abstract in Java to enable runtime polymorphism.
Derived Class :
Circle :
Attributes :
- radius (double) : Represents the radius of the circle
Method :
- getArea() : Calculates the area of a circle using the formula 𝜋 * radius2
- parameterised constructor to initialize the attribute radius.
Rectangle:
Attributes :
- length (double) : Represents the length of the rectangle.
- width (double) : Represents the width of the rectangle.
Method :
- getArea() : Calculates the area of a circle using the formula length * width.
- parameterised constructor to initialize the attribute length and width.
Refer the sample examples for understanding the output format.
Example 1:
Input : shapeType = [ "circle", "rectangle" ]
nums = [ [2] , [3, 4] ]
Output :
Area of Circle : 12.56
Area of Rectangle : 12.00
Explanation :
- Creates the object of the class Circle with radius (2) as parameter for parameterised constructor.
- Calls the getArea method to calculate and print the area of the circle.
- Creates the object of the class Rectangle with length (3) , width (4) as parameters for parameterised constructor.
- Calls the getArea method to calculate and print the area of the rectangle.
Example 2:
Input : shapeType = [ "circle", "rectangle", "rectangle" ]
nums = [ [4] , [3, 4] , [6, 2.5] ]
Output :
Area of Circle : 50.24
Area of Rectangle : 12.00
Area of Rectangle : 15.00
Explanation :
- Creates the object of the class Circle with radius (2) as parameter for parameterised constructor.
- Calls the getArea method to calculate and print the area of the circle.
- Creates the object of the class Rectangle with length (3) , width (4) as parameters for parameterised constructor.
- Calls the getArea method to calculate and print the area of the rectangle.
- Creates the object of the class Rectangle with length (6) , width (2.5) as parameters for parameterised constructor.
- Calls the getArea method to calculate and print the area of the rectangle.
Still unsure what the problem is asking ?
Let’s go through a few more examples, step by step, to make it clearer.
Constraints:
- 1 <= radius, length, width <= 104