编程新手,但构造函数似乎是一个直截了当的概念。只是无法弄清楚为什么当我在我的测试类中创建一个对象并传递参数时,他们无法初始化Polygon Class的字段。
public class Polygon{
private int numSides;
private double sideLength, xCoord, yCoord, apothem, perimeter;
public Polygon(){
this.numSides = 4;
this.sideLength = 10.0;
this.xCoord = 0.0;
this.yCoord = 0.0;
this.apothem = 5.0;
this.perimeter = 20.0;
}
public Polygon(int numSides, double sideLength, double xCoord, double yCoord, double apothem, double perimeter){
this.numSides = numSides;
this.sideLength = sideLength;
this.xCoord = xCoord;
this.yCoord = yCoord;
this.apothem = apothem;
this.perimeter = perimeter;
}
public static double getArea(double apothem, double perimeter) {
double area = .5 * apothem * perimeter;
return area;
}
public static String toString(int numSides, double sideLength, double xCoord, double yCoord, double apothem){
String results = String.format("toString() results: (numSides=%d, sideLength=%.1f%n, xCoord=%.1f%n, yCoord=%.1f%n, apothem=%.1f%n)", numSides, sideLength, xCoord, yCoord, apothem);
return results;
}
}
和测试类
public class TestPolygon {
public static void main(String[] args){
Polygon testPoly = new Polygon(4, 10.0, 0.0, 0.0, 5.0, 20.0);
String results = testPoly.toString();
System.out.println(results);
double area = testPoly.getArea();
System.out.printf("getArea() results: %.1f%n", area);
} // End main method
}
答案 0 :(得分:2)
您正在致电Polygon.toString()
,但您已实施Polygon.toString(int, double, double, double, double)
删除toString()
中的参数(覆盖Object.toString()
然后),它会正常工作。此外,它不能是static
答案 1 :(得分:1)
您的代码甚至不应该编译,因为您在没有参数的情况下调用getArea(...)
。
但话说回来,getArea首先不应该要求参数,绝对不应该是静态的。
此外,toString()
不应该是静态的,不应该使用任何参数,并且上面应该有@Override
注释。