简体   繁体   中英

Understanding java code (abstract classes, extends function)

Im trying to understand this code ...

Here is the original code:

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;
    }
}

Can someone please help me understand how this code returns 28. But also explain the part where I am getting stuck...

When dry running, I get stuck here:

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_;
    }

The main loop produces, in order, Circle(0) , Polygon(1,1) , Circle(2) , Polygon(3,3) , Circle(4) ; this is because i % 2 is 0 for even numbers and 1 for odd numbers. For the polygons, measure returns 2*(x+y), so for (1,1) you have 2*(1+1) = 4 and for (3,3) you have 2 * (3+3) = 12. For the circles, measure returns 2*r, so for (0) you have 2 * 0 = 0, for (2) you have 2 * 2 = 4, and for (4) you have 2 * 4 = 8. 0+4+4+12+8 = 28.

For the spot where you get lost, getShape(i) passes the value of i to getShape ; when i = 0 this creates a Circle, so 0 is passed to the Circle constructor, and then Circle(0) sets r to 0. Ditto if i = 2 then r = 2, and so on.

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