我构建了一个具有此方法的程序,并且我还想计算我创建的对象的数量。但是运行程序后。它说有0个对象正在创建。谁能知道为什么这是不正确的?应该说有 4 个对象被创建。这是我的代码:
/**
This program implements code for a Circle class,
which has a radius field, set and
get methods, and a getArea method.
Author: Michael Wu.
*/
public class Circle
{
private double radius;
private static int numCircles;
public Circle(double radius)
{
this.radius = radius;
}
//SetRadius method,sets radius.
public void setRadius(double radius)
{
this.radius = radius;
}
//GetRadius method; returns radius.
public double getRadius()
{
return radius;
}
//Constructor increments numbers of circles.
public Circle()
{
numCircles++;
}
//Copy constuctor.
public Circle(Circle c3)
{
radius = c3.radius;
}
//GetNumbercircles method; get number of circles.
public int getNumCircles()
{
return numCircles;
}
//Copy method, copy objects.
public Circle copy()
{
Circle copyObject = new Circle(radius);
return copyObject;
}
//Call the getArea method.
public double getArea()
{
return radius*radius*Math.PI;
}
}
/**
This program created several circle objects and then their areas and radius will be displayed on the screen.
Author: Michael Wu.
*/
public class CircleDemo
{
public static void main(String[] args)
{
int numCircles;
//Create two circle objects.
Circle c1 = new Circle(3.7);
Circle c2 = new Circle(5.9);
Circle c3 = new Circle(c1);
//Declare a circle object.
Circle c4;
//Make c3 reference a copy of a object refferenced by c1.
c4 = c2.copy();
//Display outputs.
System.out.println("The radius for circle1 is "+ c1.getRadius());
System.out.println("The area for circle1 is "+ c1.getArea());
System.out.println("The radius for circle2 is "+ c2.getRadius());
System.out.println("The area for circle2 is "+ c2.getArea());
System.out.println("The radius for circle3 is "+ c3.getRadius());
System.out.println("The area for circle3 is "+ c3.getArea());
System.out.println("The radius for circle4 is "+ c4.getRadius());
System.out.println("The area for circle4 is "+ c4.getArea());
//Get the number of circles.
numCircles = c1.getNumCircles();
System.out.println("There are "+numCircles+" objects being created.");
}
}