如何在另一个类中使用一个变量

时间:2015-01-07 03:08:24

标签: java

所以我有2节课。互动和游戏。游戏调用Interaction中返回输出的方法。方法的一个例子是walk。游戏时间可变。我需要walk方法才能改变时间值,例如time = time - 1;

我该怎么做? Game已经是Interaction的子类,允许它使用这些方法。

3 个答案:

答案 0 :(得分:1)

有几种方法可以做到这一点。你需要在Game上有setter和getter方法。你需要公开这些方法。您应该能够从Interaction for game对象访问这些方法。

如果你有时间变量protected / public,你应该可以直接从Game访问变量。

答案 1 :(得分:0)

你的调用是什么类,在另一个类中创建该类的实例:

Game game = new Game();

then use methods from within the game class:

int time = game.walk();

反之亦然:

Interaction interaction = new Interaction();

interaction.walk;

答案 2 :(得分:0)

如果游戏是互动的子类,你可以这样做:

public class Interaction {
    game g = new game();

    public void walk(){
        System.out.println(g.getTime() - 1);
    }    
    public class game{
        int time;
        public int getTime() {
            return time;
        }
        public void setTime(int time) {
            this.time = time;
        }
    }
}

在其他课程中你可以很容易地做到:

public static void main(String args[]){
    Interaction interaction = new Interaction();
    interaction.g.setTime(10);
    interaction.walk();
}
你想要这样的东西吗?或者然后发布。

Here's正在运行的代码。 (我刚刚制作Interaction class static)。 我刚刚在控制台上打印结果,你可以将它返回&按你的意愿去做。