【发布时间】:2018-09-17 23:52:30
【问题描述】:
我正在制作战舰游戏 我有 3 个班级和一个司机。
在播放器类中
我有这个方法
public void hitownshiporGrenade(String[][] grid, String attack) {
// checking if attack hits our ship, appropriate
// if it does place an s in the array
if (attack.equals(s1)) {
// -97 gives us a starting point at 0 for 'a' to
// store in array, same for 49 and '1'
grid[attack.charAt(0) - 97][attack.charAt(1) - 49] = "s ";
System.out.println("ship hit!");
s1Sunk = true;
}
我有声明的变量和顶部的吸气剂
private boolean s1Sunk;
public boolean isS1Sunk() {
return s1Sunk;
}
现在在我的另一堂课
Player player = new Player();
System.out.println(player.isS1Sunk());
如果我在驱动程序中的方法中调用它,即使第一个方法条件使其为真,它仍然是错误的;
【问题讨论】:
-
当您创建
Player的新实例时,它不会与Player的其他实例共享其状态,它们都可以有自己的isS1Sunk值。这就是 MVC 中的“模型”如此重要的地方。您需要与所有需要使用它的类共享“模型”。这也是Passing Information to a Method or a Constructor涵盖的概念 -
这样想:每次你说“新玩家”时,你都是在创建一个新玩家,所以除非你的战舰版本有很多玩家,否则你可能不应该多次调用 new。而是保存并共享 2 个玩家对象(仅调用“new”两次)
-
哦该死的,我在类中创建了很多新对象来传递方法......我对如何在没有类 name.method 的情况下传递参数有点困惑?抱歉,这是我的第一个真正的 oop 课;(