从 class 中提取方法
Extract method from class
我有一个 class 带有方法 update() 的游戏面板。如何将该方法提取到单独的文件中 (class)?
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;
}
}
我试着做了一个 class 更新:
public class Update{
private GamePanel gamePanel;
void update (){
gamePanel.move ++;
}
}
您的代码中的问题是 GamePanel.move 是私有变量,因此您无法从更新 class 访问它。您可以将此变量设置为 public
,您的 class 将起作用。
否则,如果你不想制作它 public 你可以制作它 protected
并使 Update 扩展 GamePanel,这样只有 subclass 可以访问变量
终于找到解决方案:
//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 ++;
}
}
我有一个 class 带有方法 update() 的游戏面板。如何将该方法提取到单独的文件中 (class)?
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;
}
}
我试着做了一个 class 更新:
public class Update{
private GamePanel gamePanel;
void update (){
gamePanel.move ++;
}
}
您的代码中的问题是 GamePanel.move 是私有变量,因此您无法从更新 class 访问它。您可以将此变量设置为 public
,您的 class 将起作用。
否则,如果你不想制作它 public 你可以制作它 protected
并使 Update 扩展 GamePanel,这样只有 subclass 可以访问变量
终于找到解决方案:
//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 ++;
}
}