Count number of existing objects
constructor, java, methods, object
Solution
You can have static field in your class which could be incremented in the constructor always. The reason why is it should be `static` is because, `static` fields are shared by all instances of a class, thus a local copy of the field won't be created for each of the instances you create.
private static int counter = 0;
public Die()
{
counter++;
// Other stuffs
}
// Have a getter method for the counter so that you can
// get the count of instances created at any point of time
public static int getCounter() {
return counter;
}
And then you can call the above method in your calling method like this
void someMethodInAnotherClass() {
int instanceCount = Die.getCounter(); // You need to call static method using the Class name
// other stuffs.
}
Problem
So I'm making a die class that can create and roll a die, return the value and the size. I'm trying to figure out how to tell the program how many of them have been created so that I can have a response be different based on how many there are. IE I want the response from printDie to be Die Value: 5 if there is only one die, and Die 1 Value: 5 if there is more than one. Here's my code so far. ``` package com.catalyse.die; import java.util.Random; public class Die { // instance variables private int myDieValue; private int myDieSides; private Random myRandom; // Dice Class Constructors public Die() { this.myDieValue = 1; this.myDieSides = 4; } public Die(int numSides) { if ((numSides < 4) || (numSides > 100)) { System.out.println("Error! You cannot have more than 100 sides or less than four!"); System.exit(0); } else { myDieSides = numSides; } } // getter methods public int getDieSides() { return myDieSides; } public int getDieValue() { return myDieValue; } // setter methods private void setDieSides(int newNumSides) { myDieSides = newNumSides; } public void rollDie() { Random rand = new Random(); int i = (rand.nextInt(myDieSides) + 1); myDieValue = i; } public void printDie(int dieNum) { if (dieNum == 1) { System.out.println("Die Value: "+myDieValue); } else { System.out.println("Die "+dieNum+" Value: "+myDieValue); } } ``` }