0

i have abstract class Figures and 2 inheritors. Triangle, Square and Rectangle. I need to create a static method which will use the array of figures and return the sum of their areas.

abstract class Figure { abstract double calculatePerimeter(); abstract double calculateArea() 
public class Rectangle extends Figure { double a; double b; public Rectangle(double a, double b) { this.a = a; this.b = b; } @Override double calculatePerimeter() { return 2 * (a + b); } @Override double calculateArea() { return a * b; } } 
public class Triangle extends Figure { double a; double b; double c; public Triangle(double a, double b, double c) { this.a = a; this.b = b; this.c = c; } @Override double calculatePerimeter() { return a + b + c; } @Override double calculateArea() { double p = calculatePerimeter() / 2.0; return Math.sqrt(p * (p - a) * (p - b) * (p - c)); } 

So I should create a list of figures and use in in the method, but it doesn't work

Figure[] figures=new Figure[3]; figures[1]=new Square(4.6); figures[2]=new Rectangle(4.5,5.2); figures[3]=new Triangle(6,5,2.2); 
 public static double findSquare(????????) { return square.calculateArea() + rectangle.calculateArea() + triangle.calculateArea(); 

How should it work and which topic should i read? Please explain

4
  • What is the problem ? Commented Apr 14, 2020 at 18:33
  • I guess this is something you are looking for? w3schools.com/java/java_inheritance.asp Commented Apr 14, 2020 at 18:33
  • 2
    attention this figures[3]=new Triangle(6,5,2.2); will throw exception... first index is zero. Commented Apr 14, 2020 at 18:34
  • I need to create a static method which will use the array of figures and return the sum of their areas. Commented Apr 14, 2020 at 18:40

2 Answers 2

1

Since you use inheritance and you implement calculateArea on every sub-figure (square, rectangle, triangle), all you have to do is iterate over the array of figures and sum the calculateArea on all the figures:

public static double findSquare(Figure[] arr) { double sum = 0; for (int i : arr) { sum = sum + arr[i].calculateArea(); } return sum; 

Note: I really think you should read and understand how to work with Java Inheritance and with Arrays

Sign up to request clarification or add additional context in comments.

Comments

0

You shoud loop/stream on the array then map each element to area value by calling polymorphic method calculateArea and finally make the sum.

Example with java streams :

double sumOfArea = Arrays.stream(arrayOfFigure).mapToDouble(Figure::calculateArea).sum()

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.