0

このコードを理解しようとしています...

元のコードは次のとおりです。

public class understanding {
    public static void main(String[] args) {
        int n = 5;
        Shape[] s = new Shape[n];
        for (int i = 0; i < n; i++) {
            s[i] = getShape(i);
            System.out.println(s[i]);
        }
        System.out.println(compute(s));
    }

    public static Shape getShape(int i) {
        if (i % 2 == 0) {
            return new Circle(i);
        } else {
            return new Polygon(i, i);
        }
    }

    public static double compute(Shape[] a) {
        double nc = 0;
        for (int i = 0; i < a.length; i++) {
            nc += a[i].getMeasure();
            System.out.println(a[i].getMeasure());
        }
        return nc;
    }
}

public abstract class Shape {
    protected abstract double getMeasure();
}

public class Polygon extends Shape {
    private double x;
    private double y;

    Polygon(double x_, double y_) {
        x = x_;
        y = y_;
    }

    public double getMeasure() {
        return 2 * (x + y);
    }
}

public class Circle extends Shape {
    private double r;

    Circle(double r_) {
        r = r_;
    }

    public double getMeasure() {
        return 2 * r;
    }
}

誰かがこのコードが28を返す方法を理解するのを手伝ってもらえますか.しかし、私が行き詰まっている部分も説明してください...

空運転中、ここで立ち往生します:

for(int i=0;i<n;i++){  // i=0, i<5, i++
    s[i] = getShape[i] // i=0, go to getShape class
...

getShape(i) //i=0
if (i%2==0) //TRUE so..
    return new Circle(i); //bc the boolean is True, go to Circle() class
...

Circle extends Shape{
    private double r; 
    Circle(double r_){ //I get lost here.. is r=0 now (because r_=i and r=r_)?
        r = r_;
    }
4

1 に答える 1