简体   繁体   中英

static method from abstract class

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

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

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()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM