如何在java中为数组内的对象属性设置值

时间:2014-07-10 01:13:55

标签: java arrays object setter

我一直收到这个错误:

Exception in thread "main" java.lang.NullPointerException
    at Circle.main(Circle.java:35)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
    at java.lang.reflect.Method.invoke(Method.java:597)
    at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)

我试图设置第一个圆形对象的属性,但我想我不能用java这样做吗?

public class Circle {
    private double x,
                   y,
                   radius;

    public static void main(String args[]) {
        // Testing Circles
        System.out.println("\nTESTING CIRCLES:");
        Circle[] circles = new Circle[2];
        Circle circle1 = circles[0]; // Circle 1

        // Setting X
        circle1.setX(20);  // <- Why does this not work and how is this properly done.
    }

    public void setX(double xVal) {
        x = xVal;
    }
}

1 个答案:

答案 0 :(得分:2)

您尚未初始化Circle对象,只是声明了一个适合容纳圆形对象的空数组。在声明时,数组中的所有对象都是null。在您能够调用它们上的方法之前,需要初始化数组中的对象。

Circle[] circles = new Circle[2];
circles[0] = new Circle();
circles[0].setX(20);

或者你可以按如下方式在一行中进行初始化和声明:

Circle[] circles = new Circle[] { new Circle(), new Circle() };
circles[0].setX(20);