使用Java中的数组对象从其他类调用方法

时间:2014-01-11 01:12:16

标签: java

为什么这段代码不起作用?似乎我无法使用数组将变量设置为“10”,但使用普通对象可以工作。

我做错了什么?

Class-1

public class apples {
    public static void main(String[] args) {
        carrots carrotObj = new carrots();      
        carrotObj.setVar(5);        
        System.out.println(carrotObj.getVar());

        carrots carrotArray[] = new carrots[3];
        carrotArray[1].setVar(10);        
        System.out.println(carrotArray[1].getVar());
    }
}

Class-2

public class carrots { 
    private int var = 0;
    public int getVar() {
        return var;
    }

    public void setVar(int var) {
        this.var = var;
    }
}

控制台输出:

5
Exception in thread "main" 
java.lang.NullPointerException
    at apples.main(apples.java:17)

2 个答案:

答案 0 :(得分:1)

您创建了一个数组,但是当创建一个对象数组时,它们都被初始化为null - 对象引用变量的默认值。您需要创建一些对象并将它们分配给数组中的插槽。

carrots carrotArray[] = new carrots[3];

// Place this code
carrotArray[1] = new carrots();

carrotArray[1].setVar(10);

你可以为位置0和2做类似的事情。

此外,Java约定是将类名称大写,例如Carrots

答案 1 :(得分:0)

您需要初始化数组的所有元素;由于它们不是primitive data types,因此其默认值为null

carrots carrotArray[] = new carrots[3];
for(int i=0; i < carrotArray.length; i++){
   carrotArray[i] = new carrots();
}
carrotArray[1].setVar(10);

System.out.println(carrotArray[1].getVar());
相关问题