Question

I am new to java programming and know it is possible to have class as an attribute as another.

For instance you could have publisher as one class and strategyGame as another. Is there a way to have it so a method in publisher class that counts the amount of strategyGame objects there is, therefore ability to display the amount of strategy games that publisher has published?

Thank you

Was it helpful?

Solution

Here is a simple Snippet to keep you going..

Image you have StrategyGame class

public class StrategyGame {
    private String name;

    public StrategyGame(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    } 
}

And inside your Publisher class you keep a List of StrategyGame objects

public class Publisher {

    List<StrategyGame> games;

    public Publisher() {
        games = new ArrayList<>();
    }

    public void publishGame(String name) {
        games.add(new StrategyGame(name));
    }

    public int getHowManyGamesCreated() {
         return games.size();
    }

}

Now how to use it in your main?

public static void main(String[] args) {

    Publisher publisher = new Publisher();
    publisher.publishGame("Pacman");
    publisher.publishGame("Asteroids");
    System.out.println(publisher.getHowManyGamesCreated());
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top