Search code examples
javainheritancelibgdxhierarchy

Access a child method from another child class


public class Game {
   public class Truck {
      private float x,y;
      public Truck() {}
      public float getX() {return this.x;}
      public float getY() {return this.y;}
   }
   public class Fort {
      public Fort() {
        float x = truck.getX();
        float y = truck.getY();
      }
   }

   public Truck truck = new Truck();
   public Fort fort = new Fort();
}

Beginner Java programmer trying to make a game. Getting an error when I try to get truck's x and y values to use in Fort's class method. So is it possible to call a method from another child class?

This is the error I'm getting:

Exception in thread "LWJGL Application" java.lang.NullPointerException
    at com.kroy.game.ETFortress.getTruckDistance(ETFortress.java:178)
    at com.kroy.game.ETFortress.<init>(ETFortress.java:60)
    at com.kroy.game.KroyGame.create(KroyGame.java:45)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication.mainLoop(LwjglApplication.java:151)
    at com.badlogic.gdx.backends.lwjgl.LwjglApplication$1.run(LwjglApplication.java:128)

Solution

  • That is because you are creating classes within a class.

    1. Separate the Game, Truck, and Fort classes into separate classes.
    2. In the Fort Class, create an instance of a Truck: private Truck truck;
    3. In the Fort constructor, pass a Truck as a parameter and set truck's x and y to the parameter's.
    4. Now you can access the Truck's getX() and getY() methods from within Fort.
    5. Create an instance of the Fort class in Game. Now all of your classes are connected.

    If you really are a beginner, learn the basics before trying to tackle a game. You will get there eventually, but figure out how all the pieces of code can work together first. Then you can make anything.

    Good luck!