我有3节课
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?
}
如果我在 StartGame 类中创建一个 GameInfo 类的新对象,例如
GameInfo g = new GameInfo();
int number = g.getnum(); //it returns 0
我想在数字变量中获取 10。
最佳答案
私有(private)成员(member)num
的GameInfo
默认情况下初始化为 0。如果您想退回其他东西,您必须调用g.setNum(10)
之前g.getNum()
.
关于java - 如何从另一个类访问变量 getter 和 setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28648049/