-1

I am creating a program called Humans and Pets. The program simply prints out a list of Human's names (in this case I have created 4) and their corresponding pets. Here is the code:

AmazingPets.java

public class AmazingPets {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        System.out.println("Welcome to Pets and Humans! Created By Marc B.\n____________________________\n");

        Dogs firstDog = new Dogs("Ghost");
        Humans firstName = new Humans("Alex");
        Dogs secondDog = new Dogs("Paperbag");
        Humans secondName = new Humans("Michael");
        Cats firstCat = new Cats("Tom");
        Cats secondCat = new Cats("Mr Furball");
        Humans thirdName = new Humans("Bryan");
        Humans fourthName = new Humans("Julie");
        System.out.printf("%s's dog's name is %s.\n", firstName.getHumanName(), firstDog.getDogName());
        System.out.printf("%s's dog's name is %s.\n", secondName.getHumanName(), secondDog.getDogName());
        System.out.printf("%s's cat's name is %s.\n", thirdName.getHumanName(), firstCat.getCatName());
        System.out.printf("%s's cat's name is %s.\n", fourthName.getHumanName(), secondCat.getCatName());

    }
}

Humans.java

public class Humans {
    private String mHumanName;
    public Humans(String humanName) {
        mHumanName = humanName;
    }
    public String getHumanName() {
        return mHumanName;
    }
}

I would like to create a class method called populationCount for Humans that would return the total number of Humans instances created. I would then like to output the result (using a Scanner in AmazingPets.java) to have the number of counts in the console.

Can anyone please suggest possible ways to return the total number of Humans made? as I cannot seem to find any resources online. Thank you in advance. :)

Nick L.
  • 5,151
  • 4
  • 29
  • 46
theenigma
  • 371
  • 1
  • 4
  • 6
  • 2
    On a side node, the usual convention is to keep class names in singular, e.g. `Dogs` should be `Dog`, `Cats` should be `Cat` etc. – TimoStaudinger May 23 '15 at 23:51
  • That's probably not a good way to keep track of how many humans you're working with. You'll run into issues like different parts of your code sharing the same human count even if they should only be counting their own humans, or garbage-collected humans still being included in your count. Even if you think your program isn't big enough for that kind of thing to be a problem, it's a terrible habit to get into. – user2357112 supports Monica May 23 '15 at 23:52

2 Answers2

0

Create a static field private static int humanCount = 0 and increment it in the constructor:

 public class Humans {
    private String mHumanName;
    private static int humanCount = 0;

    public Humans(String humanName) {
        mHumanName = humanName;
        humanCount++;
    }
    public String getHumanName() {
        return mHumanName;
    }
    public static int populationCount() {
        return humanCount;
    }
}

You can add a finalize() method and use it to decrement the count. It will be called when the object is destroyed.

protected void finalize( ) throws Throwable {
    humanCount--;
    super.finalize();
}
adjan
  • 12,203
  • 2
  • 25
  • 45
0

You can use this abstract class, in order to count any type of objects that inherits it. The answer is based on addy2012's answer (Thanks!):

public abstract class Countable
{
    private static final Map<Class<?>, Integer> sTotalCounts = new HashMap<>();

    public Map<Class<?>, Integer> getCountsMap() {
        return sTotalCounts;
    }

    public int getTotalCount()
    {
        return sTotalCounts.get(this.getClass());
    }

    public Countable()
    {
      int count = 0;

      //Add if it does not exist.
      if(sTotalCounts.containsKey(this.getClass()))
      {
          count = sTotalCounts.get(this.getClass());
      }
      sTotalCounts.put(this.getClass(), ++count);
    }
}

Then, you can do:

public class Dogs   extends Countable {/**/}
public class Cats   extends Countable {/**/}
public class Humans extends Countable {/**/}

Then, you can instantiate any of your objects

Dogs   dog   = new Dogs("...");
Dogs   dog2  = new Dogs("...");
Cats   cat   = new Cats("...");
Humans human = new Humans("...");

You can then get each total count by invoking the getTotalCount method from an instance:

System.out.println(dog.getTotalCount());
System.out.println(cat.getTotalCount());
System.out.println(human.getTotalCount());

Which will give you

2
1
1

Important Notes:

1) getTotalCount() is invoked via instances (non-static). This might be strange semantically, as you have a method returning a result for a total of instances, so any modification on this would be nice.

2) In order to allow the count on different types, map get & put operations are applied. Those operations have their own complexities and might be costly at cases. For more information on this, look in this answer.

Community
  • 1
  • 1
Nick L.
  • 5,151
  • 4
  • 29
  • 46