[英]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.