Reputation: 314
I'm trying to call an object from a static member class, but I get an exceptionInitializationError. Please could you look at my code and let me know what's wrong?
import java.util.ArrayList;
public class StaticInit {
public static void main(String[] args) throws Exception {
ArrayList<Olive> olives = OliveJar.olives;
for( Olive o : olives) {
System.out.println(o);
}
}
public static class OliveJar {
public static ArrayList<Olive> olives;
static {
olives.add(new Olive("Olive 1!", 10));
olives.add(new Olive("Olive 2!", 30));
olives.add(new Olive("Olive 3", 10));
System.out.println("Initialization Successful. Your Jar Contains " + olives.size() + " Olives.");
}
}
}
Upvotes: 2
Views: 70
Reputation: 77177
Your nested class has a field olives
that you never initialize, so you get an exception when calling add
. Assign an object to it:
olives = new ArrayList<>();
Additionally, both public and static fields are usually poor design. It's not clear what you're doing here, but this pattern shouldn't be used in real code.
Upvotes: 0
Reputation: 2203
Change public static ArrayList<Olive> olives;
to public static ArrayList<Olive> olives = new ArrayList<>;
.
Upvotes: 0
Reputation: 8849
initialize your array
public static ArrayList<Olive> olives=new ArrayList<Olive>();
Upvotes: 1
Reputation: 240870
ExceptionInitializerError
is becuase you haven't initialized olives
add
olives = new ArrayList<Olive>();
before adding instances to list in static initializer block
Upvotes: 1