我创建了两个圆形对象(根据我的想法)每个对象都包含不同的半径值。但是,每个Circle对象的输出都是相同的。从我对编程的理解,我的印象是,如果你没有为你的对象传递一个参数,那么该对象使用默认的构造函数。有人可以解释我错在哪里,以及如何接收两个不同半径值的圆形物体?
//create circle object use method to find area
package circle;
public class Circle {
static final double PI = 3.14;
static private double radius;
static private double area;
static private String name;
//default constructor
public Circle()
{
this.radius = 2;
}
//constructor with argument
public Circle(int radius)
{
this.name = "JOESHMO-THE-CIRCLE";
this.radius = radius;
}
public static double getRadius()
{
return radius;
}
public static double getArea()
{
//calculate area
area = PI * Math.pow(radius,2);
return area;
}
public static String getName()
{
return name;
}
public static void main(String[] args) {
Circle circle1 = new Circle(4);
Circle circle2 = new Circle();
double answer = circle1.getArea();
System.out.println(answer);
System.out.println("The radius of " + circle1.getName() + " is " + circle1.getRadius());
System.out.println(circle2.getArea());
}
}
目前的输出是:
12.56
The radius of JOESHMO-THE-CIRCLE is 2.0
12.56