【问题标题】:Extract method from class [closed]从类中提取方法[关闭]
【发布时间】:2022-01-05 12:35:35
【问题描述】:

我有一个带有方法 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 ++;
   }
}

【问题讨论】:

  • 不清楚你到底在问什么。您的问题看起来您已经有了答案:您问 “如何将该方法提取到单独的文件中”,并且您在单独的类中使用 update() 方法创建了一个类。
  • 不确定这是否是个好主意,基本上打破了封装,这是面向对象编程范式的重要特征之一
  • 可能我找到了解决方案 - 需要使用参数 GamePanel 将 Class Update 中的方法更新更改为静态并从 GamePanel 中的方法调用它:Update.update(this)。

标签: java class methods


【解决方案1】:

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

否则,如果您不想公开,可以将其设为 protected 并让 Update 扩展 GamePanel,以便只有子类可以访问该变量

【讨论】:

  • 是的,确实,我也必须将修饰符更改为受保护,谢谢。
  • 不客气。如果这解决了您的问题,请将我的答案标记为已接受!
【解决方案2】:

终于找到解决办法了:


//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 ++;
   }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-06
    • 1970-01-01
    相关资源
    最近更新 更多