我正在学习对象,我正在尝试使用引用变量作为实例变量,但即使我已经给出了值,我也会得到“java.lang.NullPointerException”。
我做错了什么?
这是我的代码:
public static void main(String[] args) {
Car car = new Car();
car.brand = "Nissan";
car.modelYear = 1998;
car.owner.name = "Marshall";
System.out.println("The car brand is "+car.brand +
"car model is "+ car.modelYear+
"cars owners name is "+ car.owner.name);
}
}
class Car {
Person owner;
String brand;
int modelYear;
int horsePower;
}
class Person {
String name;
}
答案 0 :(得分:1)
因为car.owner未初始化。
car.owner = new Person();