Can't count number of objects - java

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().

The constructors you're calling to create the objects (the ones that take a parameter) don't call the no-arg constructor that increments the counter. Try:
public Circle(double radius)
{
this();
this.radius = radius;
}
public Circle(Circle c3)
{
this();
radius = c3.radius;
}
You have to explicitly call this() otherwise the constructors will implicitly call super(), which in your case is the Object constructor.

As other answers have mentioned, you should call your zero argument constructor first via this() in each of your constructors in order to ensure that it is executed. Currently, your code does not invoke the code in the zero argument constructor since it is never called directly, nor is it called when your other constructors are invoked.
Alternatively, you could instead add an inline initialization block below your declaration, e.g:
private static int numCircles = 0;
// Increment numCircles for every object constructed.
{
numCircles++;
}
This is less standard, and possibly worse practice, but it will automatically ensure its execution without needing to increment numCircles in any constructor.

u should initialize numCircles with 0 and increase it on each constructor call, especially because u have multiple constructors u have to keep track that they are all incrementing numCircles. U can call one constructor from the inside of the other, so u may not add equal statements to each constructor.

Move your code 'numCircles++;' to Circle(double radius) constructor. Circle() is not called when you create circle object
public Circle(double radius)
{
this.radius = radius;
numCircles++;
}

Related

How do I create a loop to iterate objects and display calculations of the objects from the array?

I am new to Java and currently doing a small project to learn.
These are the requirements for the project:
Create a class named Circle with a field named radius.
Include default constructor
Include a default constructor that sets the radius to 1 by default.
Include another constructor that receives the radius and sets the radius to the value
received.
Include a method that returns the area of the circle.
-Include another method that returns the circumference of the circle.
Use the PI constant of the Math class for this calculation.
Create a class named TestCircle whose main() method declares 5 Circle objs and stores them in an array
5 circle objects will have different radius values
Using a loop, iterate the objects and display areas and circumference of the objects from the array
if the radius is one, display a message saying "This is a unit circle".
I managed to complete some of the requirements to the best of my ability but I don't know how to
Using a loop, iterate the objects and display areas and circumference of the objects from the array. If the radius is one, display a message saying "This is a unit circle".
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//constructor to receive values and set it as radius
public Circle(double [] circlesRad) {
this.radius = circlesRad[0];
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle c1 = new Circle();
double circlesRad[] = {1, 34, 56, 23, 93, 18};
for (double rad : circlesRad) {
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
if (rad == 1){
System.out.println("Circle:"+"\nArea: "+ c1.computeArea()+"\nCircumference: "+ c1.computeCircumference());
System.out.println("This is a unit circle.");
}
}
}
}
I know its very wrong, and I apologise.
Any help would be much appreciated.
Below is the code:-
class Circle {
double radius;
//constructor to default radius to 1
public Circle() {
this.radius = 1;
}
//you should consider this as just passing a radius value.
public Circle(double circlesRad) {
this.radius = circlesRad;
}
public double getRadius() {
return radius;
}
public void setRadius(double radius) {
this.radius = radius;
}
public double computeArea(){
return Math.PI * (radius * radius);
}
public double computeCircumference() {
return Math.PI *2*radius;
}
}
public class TestCircle {
public static void main(String[] args) {
Circle[] circles = {new Circle(1), new Circle(34), new Circle(56),
new Circle(23), new Circle(93), new Circle(18)};
for (Circle circle : circles) {
System.out.println("Circle:"+"\nArea: "+ circle.computeArea()+"\nCircumference: "+ circle.computeCircumference());
if (circle.getRadius() == 1){
System.out.println("This is a unit circle.");
}
}
}
}

How to effectively utilize inheritance and polymorphism on a interface

I created an interface 'Polygon' that stores the abstract methods: 'area' and 'perimeter'. However, I am not understanding how to effectively use the interface, when the classes that implement Polygon have different computations involved for calculating area and perimeter. In my opinion, I don't even need an interface 'Polygon' since it has no use in my code.
I've tried overriding the method 'area' in the Triangle class, but received the following error:
Triangle is not abstract and does not override abstract method area() in Polygon
since the Triangle area has constructors. I cannot modify the Polygon area method to have the same number of constructors needed for Triangle, because it will not then suit my Rectangle class.
public interface Polygon {
void area();
void perimeter();
}
class Triangle implements Polygon{
private double triangleArea;
private double trianglePerimeter;
public Triangle (){};
public void area(){}; //I've tried overriding method here but get a
compiler error since it is not identical to the Polygon method.
public double area(double base, double height){
triangleArea = base * height * (.5);
return triangleArea;
}
public class Project25 {
public static void main(String[] args) {
Triangle testTriangle = new Triangle();
testTriangle.area(2, 2);
testTriangle.printArea();
I've managed to obtain the answers I need in my code i.e. area and perimeter, but I need to know how to modify my code to utilize inheritance and polymorphism.
The purpose of an interface is to be an abstract view of the common features of the objects.
In case of polygons, you've already identified some things they have on common, i.e. all polygons have an area, and they all have a perimeter.
The abstract view would be to get those common values:
public interface Polygon {
double getArea();
double getPerimeter();
}
Of course, you can only get those values if the polygon is fully defined, e.g. for a triangle the base and the height might be enough to calculate the area, but not the perimeter. Instead, you usually use the lengths of the 3 sides.
public class Triangle implements Polygon {
private final double a;
private final double b;
private final double c;
public Triangle(double a, double b, double c) {
this.a = a;
this.b = b;
this.c = c;
}
#Override
public double getArea() {
// Using Heron's Formula
double p = (a + b + c) / 2;
return Math.sqrt(p * (p - a) * (p - b) * (p - c));
}
#Override
public double getPerimeter() {
return a + b + c;
}
}
A rectangle is even easier.
public class Rectangle implements Polygon {
private final double width;
private final double height;
public Rectangle(double width, double height) {
this.width = width;
this.height = height;
}
#Override
public double getArea() {
return width * height;
}
#Override
public double getPerimeter() {
return (width + height) * 2;
}
}
As you can see, since the inputs for calculating area are different, depending on the type of polygon, the area method cannot take a common set of parameters, therefore they must be embedded in the polygon object, so we can get a common area method.
I think,
Methods in Polygon interface should return values (area and perimeter).
Each shape class that implements Polygon should have its own fields and appropriate constructor to initialize them. (length and height for example), which will be used for implementation of area and perimeter.
So,
Class Triangle should have a constructor,
public Triangle (final Double base, final Double height) {
this.base = base;
this.height = height;
};
And your area method should be like,
#Override
public Double area() {
return base * height * (0.5d);
}
And you should use it something like below,
final Polygon polygon = new Triangle(13, 212);
final Double area = polygon.area();
final Double perimeter = polygon.perimeter();
The first problem I see is that you didn't declare the perimeter method in the class that implements the interface, so that would cause a compiler error right there. As to what others said, you're returning a value on both of those methods, so they shouldn't be void methods.
Also, why did you use an overloaded method in the Triangle class?

Abstract classes in java not taking any value

I am having a problem with abstract classes, the code runs but it won't take any value , it prints "0.0" everywhere, I'm thinking it is an acces problem.I have to make an abstract base class called "Point" where i declare the 3 coordinates of a point, then i have to calculate the area , volume and center point of a cube and a sphere .Also if something doesn't look good, needs formating, or don't understand a word, please tell me.Thank you.
//this is the base class
public abstract class Punct
{
public double x,y,z;
Punct(double x,double y, double z)
{
this.x=x;
this.y=y;
this.z=z;
}
public double getX()
{
return x;
}
public double getY()
{
return y;
}
public double getZ()
{
return z;
}
}
Then the sphere
//This is the sphere class that extends the Point class
public class Sfera extends Punct
{
private double aria,volumul,raza,centrul;
Sfera(double x, double y, double z,double aria,double volumul,
double centrul,double raza)
{
super(x, y, z);
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
this.raza=raza;
}
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
public double getCentrul(Punct p1)
{
return centrul;
}
}
The Cube
//this is the cube
public class Cub extends Punct
{
double latura,aria,volumul,centrul;
Cub(double x, double y, double z,double latura, double aria,double volumul, double centrul)
{
super(x, y, z);
this.latura=latura;
this.aria=aria;
this.volumul=volumul;
this.centrul=centrul;
}
public double getLatura(Punct p1,Punct p2)
{
latura=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return latura;
}
public double getAria()
{
aria=6*Math.pow(latura, 2);
return aria;
}
public double getVolumul()
{
volumul=latura*latura*latura;
return volumul;
}
}
And the Test Class where i have the main
//this is the Test class
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p1));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
Your design is really wrong. Sfera has a method getRaza() that computes the distance between two points. There's no reason to use a Sphere to compute the distance betwwen two points. This should be an instance method of Punct, that should take another point as argument.
But there's worse: instead of just computing the distance between two points, it stores this distance in the Sphere, overwriting its previous raza (not sure why a sphere has a distance):
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
You made the same mistake in several other methods: get methods should not change the state of the object.
Now, let's see your code. You start by calling
obSfera.getRaza(p1,p1)
That computes the distance between p1 and itself, so the answer is 0, and this distance is stored in the Sphere (as explained above). So, after this line of code, you've set the sphere's raza to 0. You then execute
obSfera.getAria()
and this method does
aria=4*Math.PI*raza*raza;
return aria;
so, once again, instead of just returning the area of the sphere, it overwrites its area with the computed value, which is 0 since you've set raza to 0 before.
Here's how a sphere class could look like:
public class Sphere {
private final double radius;
public Sphere(double radius) {
this.radius = radius;
}
public double getArea() {
return 4 * Math.PI * this.radius * this.radius;
}
public double getVolume() {
return (4.0 / 3) * Math.PI * this.radius * this.radius * this.radius;
}
}
Key points:
its fields are final: they can't change.
there is no need to store the volume and the area as fields, since they are derived from the radius
getters don't try to modify the object. They just compute a value and return it.
You are using the same point (p1) to calculate raza, thus replacing the value you used in the constructor. And then you used raza to calculate the other values in the Sfera class.
In the Cub class you are doing the same, so the programm is doing what it is supposed to do. If you calculate those things between the point and itself it will give you 0.
As a result the values you used in your constructor where overwritten by your methods.
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p1));
Sorry, I can't translate what is Raza, but this method calculates distance between two points.
You pass into getRaza the same point. Distance between two identical points is zero. That is why getRaza returns zero.
You assign distance between points to internal field Sfera::raza inthe method getRaza
public double getRaza(Punct p1,Punct p2)
{
raza=Math.sqrt(Math.pow(p2.x-p1.x,2)+Math.pow(p2.y-p1.y, 2)+Math.pow(p2.z-p1.z, 2));
return raza;
}
So after calling obSfera.getRaza(p1,p1) the field obSfera.raza equals to zero.
All other methods use obSfera.raza in their formulas:
public double getAria()
{
aria=4*Math.PI*raza*raza;
return aria;
}
public double getVolumul()
{
volumul=4/3*Math.PI*raza*raza*raza;
return volumul;
}
Put raza value into your formulas:
volumul = 4/3*Math.PI*raza*raza*raza = 4/3*Math.PI*0*0*0 = 0
aria = 4*Math.PI*raza*raza = aria=4*Math.PI*0*0
The same is happening with the object obCub
create another object for class Punct and rewrite the code like below:
public class TestTema
{
public static void main(String[] args_)
{
Punct p1=new Punct(2, 2, 2) {};
Punct p2=new Punct(3, 3, 3) {};
Sfera obSfera=new Sfera(1,2,3,1,1,1,1);
System.out.println("Raza sfera:" + obSfera.getRaza(p1,p2));
System.out.println("Aria sfera=" + obSfera.getAria());
System.out.println("Volum sfera= " +obSfera.getVolumul());
// System.out.println("Centrul= "+obSfera.getSuprafata());
Cub obCub=new Cub(1,2,3,1,1,1,1);
System.out.println("Lungime latura cub:"+obCub.getLatura(p1,p2));
System.out.println("Aria cubului="+obCub.getAria());
System.out.println("Volumul cubului="+obCub.getVolumul());
// System.out.println("Suprafata="+obCub.getCentrul());
}
}
classes Cub and Sfera both refering the same object p1, so the distance value Math.pow(p2.x-p1.x,2) always be 0.

Adding objects with different parameter into the array

So I have this question,
Class circle:
Contains an appropriate attribute to store the radius.
Contains a constructor with one parameter to set the radius.
Contains set and get methods.
Contains a method for calculating the area and another method for calculating the
circumference.
Circle should contain an appropriate attribute to keep track (count) of the number of
Circle objects instantiated.
Class TestCircle:
Create an array of 10 circles of radii 1.0 , 2.0, ..., 10.0.
Print the area and circumference of each circle.
Retrieve and print the number of circles that have been instantiated.
My code is:
public class Circle {
public double radius= 0.0;
public int counter;
public Circle (double radius){
this.radius = radius;
counter++;
}
public Circle (){
}
public void setRadius (double radius){
this.radius = radius;
}
public double getRadius (){
return radius;
}
public double Area (){
return 3.14*radius*radius;
}
public double Circumference (){
return 2*3.14*radius;
}
}
public class TestCircle {
public static void main (String args []){
Circle [] arr = new Circle [10];
System.out.println ("The circumference" + arr.Circumference());
System.out.println ("The area" + arr.Area());
System.out.println ("The number of circles" + arr.counter);
}
}
My question is:
How am I supposed to create 10 circle objects with different radius and add it to the array?
I know that the idea was to add the objects to the array by using the for loop but I couldn't add the radius into the process.
Thank you.
Your code could change like
public class Circle {
private double radius;
private static int numberOfCircles = 0;
public Circle (double radius){
this.radius = radius;
numberOfCircles++;
System.out.println("The circumference : " + getCircumference());
System.out.println("The area : " + getArea());
}
public double getRadius (){
return radius;
}
public double getArea (){
return 3.14*radius*radius;
}
public double getCircumference (){
return 2*3.14*radius;
}
public static int getNumberOfCirclesCreated(){
return numberOfCircles;
}
}
public class TestCircle {
public static void main (String args []) {
Circle [] circles = new Circle [10];
for(int counter=0;counter< circles.length;counter++){
circles[counter]=new Circle((double)(counter+1));
}
System.out.println("Number of circles : " + Circle.getNumberOfCirclesCreated());
}
}
Create for loop that iterates through each array cell. You then create a new Circle object and call its setRadius function. You then set array Cell to equal the Circle object and continue iterating till the array is filled.
Additionally, your counter should be static (as corrected by Fildor). Consider also setting radius as private, seeing as you put in getter/setters.

Java object returning zeros for calculated variables

this is my first question here and I'm very new to programming so please bear with me.
I'm taking a java class, and in my current assignment I have to create three instances of a circle, compute their diameters and areas, and print the values. The first two instances are supposed to have the radius set by a setRadius method, while the third is supposed to retain the default calculations based on a radius of 1.
edit: The problem is this: the first two objects, on which I used the setRadius method, returned correct values, but the third was intended to return default values of the constructor, and instead it returned all zeros.
Here is the code, thanks in advance!
//this class implements the Circle class
public class TestCircle
{
public static void main(String[] args)
{
Circle Circle1 = new Circle();
Circle Circle2 = new Circle();
Circle Circle3 = new Circle();
Circle1.setRadius(2);
Circle2.setRadius(10);
Circle1.display();
Circle2.display();
Circle3.display();
}
}
import java.lang.Math.*;
public class Circle
{
double radius;
double diameter;
double area;
public void Circle()
{
radius = 1;
diameter = radius * 2;
area = (radius * radius) * Math.PI;
}
public void setRadius(double rad)
{
this.radius = rad;
diameter = radius * 2;
area = (radius * radius) * Math.PI;
}
public void display()
{
System.out.println("Radius: " + radius);
System.out.println("Diameter: " + diameter);
System.out.println("Area: " + area);
}
}
This
public void Circle()
is just a method with a void return type. For a constructor, you need
public Circle() // notice there is no return type
Because you didn't actually provide a constructor, the following
Circle Circle1 = new Circle();
Circle Circle2 = new Circle();
Circle Circle3 = new Circle();
used a default constructor provided by the compiler. It has an empty body and thus the field values are all initialized to 0 by default.
And since you only call setRadius() on two of them, the other one will only show values of 0.
Read up on constructors here.
Java naming conventions state that variable names should start with lowercase letters and follow a camelCase format. You can do some further reading on this subject here.

Categories