[英]NullPointerException 7
我在同一包中有3个与问题相关的类:MainClass,Player和Ground。 在Player.java中,我需要访问MainClass中声明的变量,如下所示:
private static Ground ground;
...
ground= new Ground(440);
还有一个我要使用的吸气剂。 这是Ground.java:
package cratejumper;
public class Ground {
private int Y;
public Ground(int height) {
Y = height;
}
public int getY() {
return Y;
}
public void setY(int y) {
Y = y;
}
}
现在,我像这样从Player.java中的MainClass.java访问地面:
private static Ground ground = MainClass.getGround();
但是,当我尝试访问Player.java中的ground.getY()时,它将在运行时引发nullpointerexception。 在Eclipse中编写代码时,我没有任何错误。 这是我想在Player.java中使用地面的部分
39 if (Y + speedY >= ground.getY()-HEIGHT) {
40 Y = ground.getY()-HEIGHT;
41 speedY = 0;
42 jumped=false;}
我找不到错误! 基本上,我对另一个名为Background.java的类也做了同样的事情。
private static Ground ground;
上面的行在MainClass类加载时执行(大概是在应用程序的最开始)。 执行此行后,ground为空。
private static Ground ground = MainClass.getGround();
上一行是在加载Player类时执行的(大概是在应用程序的最开始)。
最后
ground= new Ground(440);
已执行,但我们不知道何时执行,因为我们没有完整的代码。 但是大概是在Player类加载之后执行的。
非恒定静电场通常是设计不良的标志。 考虑传递对象,而不是使用静态字段。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.