I have a class of objects:
public class SubObjects {
int depth;
public SubObjects(int d) {
this.depth = d;
}
}
And then another class of objects:
import java.util.ArrayList;
public class Objects {
private int height;
private int width;
ArrayList<SubObjects> liste;
public Objects(int h, int w) {
this.height = h;
this.width = w;
}
}
The idea here is that each object should be able to hold a height value, a width value and a list of SubObjects.
E.g. = 2,4,[SubObject1, SubObject2]
The following being the main class:
import java.util.*;
public class Tryout {
public static void main(String[] args) {
SubObjects S1 = new SubObjects(7);
SubObjects S2 = new SubObjects(9);
Objects O1 = new Objects(2,4);
O1.liste.add(S1);
O1.liste.add(S2);
System.out.println(O1);
}
}
First I create two SubObjects.
Then I create an Object with the ints 2 and 4.
Where everything goes astray is the next line:
O1.liste.add(S1);
The error code given:
Cannot invoke "java.util.ArrayList.add(Object)" because "O1.liste" is null
Now I get that the array list is null, I have not added anything yet of course, but why can't I add anything to it?