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

2

循环按main顺序产生, Circle(0), Polygon(1,1), Circle(2), Polygon(3,3); Circle(4)这是因为i % 2偶数为 0,奇数为 1。对于多边形,measure返回 2*(x+y),因此对于 (1,1),您有 2*(1+1) = 4,对于 (3,3),您有 2 * (3+3) = 12。对于圆圈,measure返回 2*r,因此对于 (0),您有 2 * 0 = 0,对于 (2),您有 2 * 2 = 4,对于 (4),您有 2 * 4 = 8. 0+4 +4+12+8 = 28。

对于迷路的地方,getShape(i)将 的值传递igetShape; when i= 0 this 创建一个 Circle,so0被传递给 Circle 构造函数,然后Circle(0)设置r为 0。同上 if i= 2 then r= 2,依此类推。

于 2013-04-17T17:19:21.417 回答