In my enum constructor, I'm trying to initialize their members. I need to use a switch statement to know which enum is currently being instantiated. However for some reason this
seems to return null
which makes little sense to me. Is this
null
until the constructor completes? If so, how can I differentiate which enum is being constructed at run time? The example below is a simplified version of my actual code to demonstrate the problem.
Food f = Food.APPLE;
System.out.println(f.getTastes());
Food Enum
public enum Food
{
APPLE,
PANCAKES,
PASTA;
private List<String> tastes = new ArrayList<>();
Food()
{
switch(this)
{
case APPLE:
tastes.add("Sour");
tastes.add("Sweet");
break;
case PANCAKES:
tastes.add("Dough-y");
break;
case PASTA:
tastes.add("Creamy");
tastes.add("Rich");
tastes.add("Velvet");
}
}
public List<String> getTastes()
{
return tastes;
}
}
I get the following exception
Exception in thread "main" java.lang.ExceptionInInitializerError
at Food.<init>(Food.java:18)
at Food.<clinit>(Food.java:10)
at Tester.main(Tester.java:9)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.NullPointerException
at Food.values(Food.java:8)
at Food$1.<clinit>(Food.java:18)
... 8 more