java - 构造函数创建多个变量,如何通过其他方法返回它们?

标签 java variables constructor

public class Game {

    public Game(
        boolean createstage, //For sorting purposes
        int slength, 
        int sheight, 
        boolean createplayer, 
        int plength, 
        int pheight, 
        boolean playersprite,
        BufferedImage psprite, 
        boolean defaultcontrols,
        String pcontrols, 
        boolean test
        ) {
    if(test == true) { //if test is true, test
        new Test();
    }else{ //otherwise create a stage is createstage is true and
        if(createstage == true) {
            StageObj gamestage = new StageObj(slength, sheight);
        }
        if(createplayer==true) {
            PlayerObj player = new PlayerObj(plength, pheight, psprite, pcontrols);
        }
    }
}

public Game() {
    new StageObj(100, 100);
    new PlayerObj(10, 10);
}

public StageObj givestageobj() {
    return gamestage;
}

public PlayerObj giveplayerobj() {
    return player;
}

}

我的构造函数的代码和两个旨在返回构造函数中创建的变量的变量也是如此。问题是方法 Giveplayerobj 和 Givestageobj 都找不到变量 gamestage 和player。这是有道理的,但是我如何在构造函数中创建变量,然后以某种方式将它们传递给 Giveplayerobj() 和 Givestageobj() 变量,以便理论上有人可以转到 Game.giveplayerobj() ,它返回在构造函数中创建的playerobj?

谢谢

-JXP

最佳答案

您需要将它们声明为类属性,而不是在构造函数内才能正常工作。因此,您的代码应如下所示。

变化:

  1. 我添加了两个类变量 StageObj 和 PlayerObj,因为您已经为它们准备好了 getter。
  2. 从构造函数内部删除了这两个变量的声明。
  3. 添加了对覆盖默认构造函数的赋值。 (可能是您试图使用默认构造函数实现的目标)

    public class Game {
    
    private StageObj gamestage = null;
    private PlayerObj player = null;
    
    public Game(
        boolean createstage, //For sorting purposes
        int slength, 
        int sheight, 
        boolean createplayer, 
        int plength, 
        int pheight, 
        boolean playersprite,
        BufferedImage psprite, 
        boolean defaultcontrols,
        String pcontrols, 
        boolean test
        ) {
    if(test == true) { //if test is true, test
        new Test();
    }else{ //otherwise create a stage is createstage is true and
        if(createstage == true) {
            gamestage = new StageObj(slength, sheight);
        }
        if(createplayer==true) {
            player = new PlayerObj(plength, pheight, psprite, pcontrols);
        }
    }
    }
    
    public Game() {
        gamestage = new StageObj(100, 100);
        player = new PlayerObj(10, 10);
    }
    
    public StageObj givestageobj() {
        return gamestage;
    }
    
    public PlayerObj giveplayerobj() {
        return player;
    }
    
    }
    

关于java - 构造函数创建多个变量,如何通过其他方法返回它们?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9840480/

相关文章:

css - 动态引用 sass/scss 变量

c# - 在 C# 中,进行构造函数链接的最佳/可接受的方式是什么?

java - 如何在 sqlite4java 中禁用自动提交?

java - MismatchedInputException - Jackson 反序列化

powershell - 为什么不能使用 VariablesToExport 导出 PowerShell 模块中的变量成员?

python - 获取变量名作为字符串

java - 泛型类类型中的参数化方法

java - 在 switch case java 中使用数组

当我调用新的构造函数时,java运行得太快

ios - Swift nsobjecttype 构造函数