当我尝试将Instance变量文件作为Refrence变量文件打印时,为什么会出现异常?

时间:2016-06-19 20:34:58

标签: java object printing instance-variables

我正在学习对象,我正在尝试使用引用变量作为实例变量,但即使我已经给出了值,我也会得到“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;
}

1 个答案:

答案 0 :(得分:1)

因为car.owner未初始化。

car.owner = new Person();