【问题标题】:Interacting classes in Java. How much interaction is possible?Java中的交互类。有多少互动是可能的?
【发布时间】:2014-01-08 20:43:13
【问题描述】:

我是 Java 编程新手,我知道可以将类作为属性作为另一个属性。

例如,您可以将发布者作为一个类,将 strategyGame 作为另一个类。有没有办法让发布者类中的一个方法计算存在的 strategyGame 对象的数量,从而显示发布者已发布的策略游戏的数量?

谢谢

【问题讨论】:

  • 是的...您跟踪您创建的Objects

标签: java class attributes object-oriented-analysis


【解决方案1】:

这里有一个简单的片段让你继续前进..

你有StrategyGame类的图片

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

在您的 Publisher 类中,您保留了一个 StrategyGame 对象列表

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

}

现在如何在您的main 中使用它?

public static void main(String[] args) {

    Publisher publisher = new Publisher();
    publisher.publishGame("Pacman");
    publisher.publishGame("Asteroids");
    System.out.println(publisher.getHowManyGamesCreated());
}

【讨论】:

  • 你说的很有道理。它没有通知我你的回答,所以很抱歉回复晚了。这比我想象的要简单得多。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-11-01
  • 2018-01-31
  • 2016-02-25
  • 2020-06-15
相关资源
最近更新 更多