我对父类中的初始化感到困惑。我需要对其工作原理的简要解释。
public class Bullet extends NextUnit {
public static int numBullets;
public Bullet() {
super();
}
public Bullet(GameMain gameMain, AnimInfo animInfo, double x,double y, double xOnMap, double yOnMap,
double degree, double speed, double speedBackward, double speedRotate, int state) {
super(gameMain, animInfo, x, y, xOnMap, yOnMap, degree, speed, speedBackward, speedRotate, state);
}
// other parts of code are omitted
}
我在哪里初始化 numBullets?
最佳答案
您打算将其声明为静态吗?静态变量将被所有实例共享。您可以简单地内联设置其值(如果它是常量)或在其他地方进行一次赋值。
如果它不打算在“bullet”的所有实例之间共享,则删除 static
并将其设置为每个构造函数中有意义的任何默认值(在 super 之前或之后)。如果您需要其他参数,只需添加它们即可。
您打算计算已实例化的 Bullet
数量吗?然后你只需在两个构造函数中将其初始化为 0 并加一即可。
关于java - 在扩展类中初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079955/