Question

I made a class that can be called upon to to store the x and y values for my classes. However, when I call the super constructor the values are not being passed.

This is where I make a new instance of the Player class in my main class.

p = new Player(getWidth() / 2, getHeight() / 2, this);

This is my class I am calling upon for my super constructor

public class GameObject {

public int x;
public int y;
public GameObject(int x, int y){    
    this.x = x;
    this.y = y;
}
}

Here is my class calling the super constructor

public class Player extends GameObject implements EntityA{

private int x = 0;
private int y = 0;
Game game;
BufferedImage spriteSheet;
Rectangle bounds;

public Player(int x, int y, Game game){
    super(x, y);
    this.game = game;
    bounds = new Rectangle(x, y, Game.spriteSize, Game.spriteSize);
    spriteSheet = game.getSpriteSheet();
    System.out.println("x: " + this.x + " this.y: " + y);

}

Both x and y have values of zero. I can see I am not using the call to the super constructor correctly. Can someone tell me how this can be done. Thank You.

Was it helpful?

Solution

In your Player constructor, this line

System.out.println("x: " + this.x + " this.y: " + y);

is using the Player version of x and y, which are being ignored by your code, and therefore have the default initial values for ints, which is zero. I think you want to eliminate this

private int x = 0;
private int y = 0;

from your Player class, which would then cause your code to access the GameObject version of x and y, which is your goal.

OTHER TIPS

The problem lies not in the constructor, but in the fields of these classes. You define a public int x and y in GameObject, and also a private int x and y in Player.

The GameObject.x will get hidden by Player.x. However, the constructor for GameObject still sets GameObject.x to the given value. If you then try to query what Player.x is, then yes it is still zero.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top