Shape and Overriding

Easy
0/40
55 upvotes
Asked in companies
SAP LabsMetricStreamAmdocs

Problem statement

Create a Class Shape having a field shapeType and a function printMyType.

Create another class, Square and Rectangle, which inherits the Shape class and has additional fields length and breadth. Both Square and Rectangle classes will have two functions calculateArea, which will return the object's area, and printMyType, which will print the type of the object.

Inside the main, first create the object of class Square and have a length equal to 5 and call the printMyType then calculateArea method after creating the object of class Rectangle having the length equal to 5 and breadth equal to 4 and again call the printMyType and calculateArea method.

Sample Output 1 :
square
25
rectangle
20
Explanation of Sample output 1:
Firstly we are creating the object of class Square with mentioned length 5 and calling the functions printMyType which output square and then calculateArea which returns 25 and hence printed. Similarly, it is done for the Rectangle class.
Approaches (1)
Intuitive Approach
  • In the code, there is a class Shape has an attribute shapeType after that, we have class Square and Rectangle, which is inheriting the property of class Shape and has an additional attribute length, length, and breadth, respectively.
  • After that, we first create an object s of Square class and passed the length of a square, creating an object calling printMyType and calculateArea method, respectively.
  • Here printMyType of Shape Class is getting overridden in the Square and Rectangle Class.
Time Complexity
Space Complexity
Code Solution
(100% EXP penalty)
Shape and Overriding
Full screen
Console