Taylor
Taylor

Reputation: 405

Count number of existing objects

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);
    }
}

}

Upvotes: 4

Views: 39239

Answers (4)

Dhiral Pandya
Dhiral Pandya

Reputation: 10619

See what is my solution for counting objects in my application

import java.util.Map;
import java.util.TreeMap;

public abstract class ObjectCounter {

    private static Map<String, Long> classNameCount = new TreeMap<String, Long>();

    public ObjectCounter() {
        String key = this.getClass().getName();
        if (classNameCount.containsKey(key)) {
            classNameCount.put(key, classNameCount.get(key) + 1);
        } else {
            classNameCount.put(key, 1L);
        }
    }

    public static <T extends ObjectCounter> long getCount(Class<T> c) {
        String key = c.getName();
        if (classNameCount.containsKey(key)) {
            return classNameCount.get(key);
        } else {
            return 0;
        }
    }

    public static long totalObjectsCreated() {
        long totalCount = 0;

        for (long count : classNameCount.values()) {
            totalCount += count;
        }

        return totalCount;
    }

} 

Now extends ObjectCounter class

See below

package com.omt.factory;

public class Article extends ObjectCounter {

}

Now all your other classes are extending Article classes

package com.omt.factory;

public class Bio extends Article {

}

Now here is our main class

package com.omt.factory;

public class Main {

    public static void main(String... a) {
        Bio b = new Bio();
        Bio b1 = new Bio();
        Bio b2 = new Bio();
        Bio b3 = new Bio();
        Bio b4 = new Bio();
        com.omt.temp.Bio bio = new com.omt.temp.Bio();

        // Total Objects are created
        System.out.println("Total Objects Created By Application :" + ObjectCounter.totalObjectsCreated());
        // Get Number Of Objects created for class.
        System.out.println("[" + com.omt.temp.Bio.class.getName() + "] Objects Created :"
                + ObjectCounter.getCount(com.omt.temp.Bio.class));
        System.out.println("[" + Bio.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Bio.class));
        System.out.println("[" + Maths.class.getName() + "] Objects Created :" + ObjectCounter.getCount(Maths.class));

    }

}

From this article

Upvotes: 0

Paul Samsotha
Paul Samsotha

Reputation: 208944

Use a static variable

public class Die{
    static int dieCount = 0;

    public Die(){
        dieCount++;
    }
}

Every time a Die object is created, the count will increase

public static void main(String[] args){
    Die die1 = new Die();
    Die die2 = new Die();

    int count = Die.dieCount;

}

Upvotes: 0

Rahul
Rahul

Reputation: 45060

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.
}

Upvotes: 9

Christian Tapia
Christian Tapia

Reputation: 34146

Use an static member, that is a 'class' variable, not a 'instance' variable:

private static int count = 0;

In the constructor:

public Die()
{
    count++;
    this.myDieValue = 1;
    this.myDieSides = 4;
}

And a getter:

public static int getCount() {
    return count;
}

Upvotes: 3

Related Questions