为什么这段代码不起作用?看来我无法使用数组将变量设置为“10”,但使用普通对象就可以了。
我做错了什么?
类别- 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());
}
}
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)
最佳答案
您创建了一个数组,但是当创建对象数组时,它们都被初始化为null
——对象引用变量的默认值。您需要创建一些对象并将它们分配给数组中的槽。
carrots carrotArray[] = new carrots[3];
// Place this code
carrotArray[1] = new carrots();
carrotArray[1].setVar(10);
您可以对位置 0 和 2 执行类似的操作。
此外,Java 约定是将类名大写,例如胡萝卜
。
关于java - 在Java中使用数组对象调用其他类的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21057280/