简体   繁体   中英

Calling methods from other classes using array objects in Java

Why does this code not work? It seems I cannot set the variable to '10' with the Array, but with a normal object it works.

What am I doing wrong?

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;
    }
}

Console Output:

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

You created an array, but when an array of objects is created, they are all initialized to null -- the default value for object reference variables. You need to create some objects and assign them to slots in the array.

carrots carrotArray[] = new carrots[3];

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

carrotArray[1].setVar(10);

You could do something similar for position 0 and 2.

Additionally, the Java convention is to capitalize class names, eg Carrots .

You need to initialize all the elements of the array; since they are not primitive data types their default value is 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());

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM