从类中提取方法



我有一个带有update((方法的类GamePanel。如何将该方法提取到单独的文件(类(中?

public class MainThread{ 
GamePanel gamePanel;
public MainThread(GamePanel gamePanel){
this.gamePanel = gamePanel;
} 

void run (){
gamePanel.update();
}
}
public class GamePanel {
private int move = 0;
void update (){
move ++;
}
void calculate (){
if (move > 5)
move = 0;
}
}

我试着做一个类更新:

public class Update{
private GamePanel gamePanel;
void update (){
gamePanel.move ++;
}
}

代码中的问题是GamePanel.move是一个私有变量,因此您无法从Update类访问它。您可以将这个变量设为public,这样您的类就可以工作了。

否则,如果你不想公开它,你可以将其设为protected,并使Update扩展GamePanel,这样只有子类可以访问变量

最终找到了解决方案:


//method update in GamePanel should be like this:
protected int move = 0;
public void update() {
Update.update(this);
}
//Class Update:
public class Update{

public static void update(GamePanel gamePanel) {
gamePanel.move ++;
}
}

最新更新