Search code examples
javaabstract-classbluejmethod-call

How to call a method from within an abstract class


I'm making a game with one of my friends. I am trying to call a method's return value to another method in the same class. I know how to do this under normal circumstances, but the class I'm using is abstract. I have looked over the internet for the answer, but I haven't found anything. This is the bit of code that I'm using:

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
  }
 }

Solution

  • Abstract classes can't be used directly. You need to have an actual specialized class to use it. Then, as your methods are static, instead of using an instance of the specialized class, you just use the name of the base class, like this:

    int x = SpecializedClassName.MoveX(1);
    

    That can happen from anywhere, as static methods are always available.

    Or, alternatively, you could simply use

    int x = Game.MoveX(1);