【问题标题】:Super Constructor not passing values to render method超级构造函数没有将值传递给渲染方法
【发布时间】:2014-03-12 02:46:43
【问题描述】:

我创建了一个类,可以调用它来存储我的类的 x 和 y 值。但是,当我调用超级构造函数时,值并没有被传递。

这是我在主类中创建 Player 类的新实例的地方。

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

这是我为我的超级构造函数调用的类

public class GameObject {

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

这是我的类调用超级构造函数

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);

}

x 和 y 的值都为零。我可以看到我没有正确使用对超级构造函数的调用。有人可以告诉我如何做到这一点。谢谢。

【问题讨论】:

    标签: java constructor super


    【解决方案1】:

    在您的 Player 构造函数中,这一行

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

    正在使用xyPlayer 版本,您的代码将忽略它们,因此具有整数的默认初始值,即零。我想你想消除这个

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

    来自您的 Player 类,这将导致您的代码访问 GameObject 版本的 xy,这是您的目标。

    【讨论】:

      【解决方案2】:

      问题不在于构造函数,而在于这些类的字段。在GameObject 中定义public int xy,在Player 中定义private int xy

      GameObject.x 将被Player.x 隐藏。但是,GameObject 的构造函数仍将 GameObject.x 设置为给定值。如果您随后尝试查询 Player.x 是什么,那么是的,它仍然为零。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-05-03
        • 2019-03-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-09-10
        相关资源
        最近更新 更多