Task 9 - Polymorphism in Java

9.1: Make Circle, Rectangle, Square and Triangle classes that extends Shape. Shape has color attribute and an abstract double calcArea() method. Circle has radius attribute. Triangle has base and height. Rectangle has length and width. Square have only one attribute i.e. size (to represent width and height both, as both are same in case of square).

In ShapeTest class's main method, ask the user how many shapes he want to create. Then, ask the type of each shape, then get the required data to instantiate that shape object. Keep putting each shape in ArrayList of type Shape.

e.g. How many shapes you want to create: 4
Choose 1st Shape type:
Press 1, to create Circle
Press 2, to create Rectangle
Press 3 to create Triangle
Press 4 to create Square
Enter the radius of circle: > 5

Then outside the loop, display following information:
  1. Sum of area of each shape type 
  2. Total shapes of each shape type
  3. Total cost to paint each shape type 
  4. Cost to paint all shapes
You may define a calcPaintingCost in Painter class. That shall receive a Shape argument and return the painting cost with respect to its area using a static final per unit painting rate.

Define static method in ShapeTest, printData(ArrayList<Shape> shapes), it shall display above mentioned information is given formate: 
Total circles: 10,        Total area of all circles: 1200          Painting cost: 1000
Total rectangles: 20,  Total area of all rectangles: 600      Painting cost: 6000
Total triangles: 30,    Total area of all triangles: 1000       Painting cost: 1000
Total squares: 10,      Total area of all squares: 600          Painting cost: 6000

Total painting cost: 14000

(Above values of totals are just examples, you must calculate correct values as per size of shape collection passed in method)


  1. sir abstract method ko jb overide kiya to main class mein call kesay ho ga


Post a Comment