有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java如何从另一个类访问变量getter和setter

我有三节课

public class GameInfo 
{
  private  int num;
  public void setNum(int num){
         this.num=num;
    }
  public int getNum(){
         return num; 
   }
}

public class NewGame
{ 
  public void foo(){
    GameInfo g = new GameInfo();
    g.setNum(10);
}
}

public class StartGame()
{
   //i want to access the num in GameInfo being set by NewGame class. How to do that? 

}

如果我在StartName类中创建GameInfo类的新对象,如

GameInfo g = new GameInfo();
int number = g.getnum(); //it returns 0

我想在数字变量中得到10


共 (2) 个答案

  1. # 1 楼答案

    GameInfo的私有成员num按默认值初始化为0。如果要返回其他内容,必须在g.getNum()之前调用g.setNum(10)

  2. # 2 楼答案

    Sinenum变量是GameInfo类的实例成员,因此每次创建GameInfo的新对象时,num的值都将设置为默认值,即0

    因此,为了获得10作为getnum()方法的返回,首先需要在同一对象引用上调用setter方法作为setnum(10)

    public class StartGame() {
        NewGame newGame = new NewGame();
        newGame.foo();  // It sets 10, but this value will only be accessible from your NewGame's instance.
        GameInfo info = new GameInfo();
        info.setnum(10);  // It sets num to 10
        int number = info.getnum(); //it returns 10
    }