Count Number of Objects in Java

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


Source: oop

Leave a Reply