我试着去理解这段代码...了解Java代码(抽象类,扩展功能)
这里是原代码:
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_;
}
我可以问,你有理解类继承,多态性和相关或只是与此代码?如果是第一种选择,我建议你回顾一下这些话题,并从一些简单的事情开始,然后一步一步来。如果是第二种选择,请**调试**代码或使用另一个系统查看逐行发生的事情。 –