繁体   English   中英

如何从抽象类中调用方法

[英]How to call a method from within an abstract class

我正在和一个朋友一起做游戏。 我试图将一个方法的返回值调用到同一类中的另一个方法。 我知道在正常情况下如何执行此操作,但是我正在使用的类是抽象的。 我已在互联网上寻找答案,但没有发现任何东西。 这是我正在使用的部分代码:

public abstract class Game implements ActionListener 
{
   public static char KBoard(char w, char a, char s, char d) //This method takes in a keyboard command from the user, and returns that char.
{
      Scanner scan = new Scanner(System.in);
      System.out.print("");
      char kBoard = scan.next().charAt(0);
      return kBoard;
   }

   public static int MoveX (int velocity) 
{
      velocity = 5;//character moves this distance when a control key is pressed

      Game kBoard = new Game();//These lines here will
      kboard.KBoard();//call the KBoard method from above and the char it returns^^
      Switch ();
      {
        Case w:
        characterPosX -= velocity;//if the w key is pressed, character moves up
        break;

        Case s:
        characterPosX += velocity;//if the s key is pressed, character moves down
        break;
     }
    return characterPosX;//returns the new X position for the game character
  }
 }

您不能创建abstract class instance ,也不需要create对象来调用static方法。 相反,请执行以下操作-

Game.KBoard();

抽象类不能直接使用。 您需要有一个实际的专门班级才能使用它。 然后,由于您的方法是静态的,因此您无需使用专用类的实例,而只需使用基类的名称即可,如下所示:

int x = SpecializedClassName.MoveX(1);

这可以在任何地方发生,因为静态方法始终可用。

或者,您也可以简单地使用

int x = Game.MoveX(1);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM