數組初始化問題
執行下面的代碼時:
class Wheel{
public void display(int d){
System.out.println("Wheel["+d+"]");
}
}
public class Car {
private Wheel[] wheel=new Wheel[4];
private static int[] con=new int[4];
public Car() {
}
public static void main(String[] args) {
Car car=new Car();
System.out.println(con[2]);
car.wheel[0].display(0);
}
}
結果如下
0
Exception in thread “main” java.lang.NullPointerException
at Car.main(Car.java:16)
分析如下
錯誤定位在:
car.wheel[0].display(0)
錯誤信息是:空指針異常
而同樣都是數組,同樣的初始化,int類型的con卻可以直接調用,wheel卻不可以。由此發現基本類型數組和非基本類型數組在初始化時存在差異:
基本類型的數組如果沒有賦初值的話,java會根據它的類型給一個默認的初值。非基本類型的數組存放的是引用類型,只有當生成對象後,引用才指向對象,否則引用爲null。
說明:
private Wheel[] wheel=new Wheel[4];
此時還沒生成對象,引用爲空,所以會報NoPointerException。
更正
class Wheel{
public void display(int d){
System.out.println("Wheel["+d+"]");
}
}
public class Car {
private Wheel[] wheel=new Wheel[4];
private static int[] con=new int[4];
public Car() {
for(int i=0;i<4;i++){
wheel[i]=new Wheel();
}
}
public static void main(String[] args) {
Car car=new Car();
System.out.println(con[2]);
car.wheel[0].display(0);
}
}
更正後的運行結果
0
Wheel[0]