I built a program that has this method and I also want to count the number of objects I created. But after running the program. It said that there are 0 objects being created. Can anyone know why this is not correct? It should say that there are 4 objects being created. Here is my codes:
/**
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.");
}
}
You only increment numCircles when you call the Circle constructor with no arguments. But you never call that specific constructor; you call the other constructors.
Increment numCircles on all constructors.
Incidentally, because numCircles is static, the method getNumCircles that returns this number should also be static, and you could invoke it as follows: Circle.getNumCircles().
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With