TheLostMind TheLostMind - 3 years ago 110
Java Question

Why does Java allow null value to be assigned to an Enum

This is more of a design question. (So, No code. I could post code of creating an Enum and assigning it to null if you want me to do it. :)) I've been thinking a lot about this lately but can't come up with one good reason. The Enum constants are implicitly static and final. Enum is meant to say - "I can take a value of one of the constants present in me". Why allow Enum to have a null value?. Why not implicitly default the Enum's value to a Enum.DEFAULT or Enum.None?. Isn't this a better approach than allowing the Enum to be null?

Answer Source

Firstly null means non-existence of an instance. Providing a default constant like DEFAULT or NONE, will change that meaning. Secondly, why would you need something default to represent what seems to be non-existent? That is the purpose of null. Basically, you would have to initialize and store an extra object, which shouldn't even exist whatsoever.

BTW, it's not a language choice. It's completely on you how you implement your enum. You can provide another constant like DEFAULT, or UNKNOWN in your enum, and avoid the assignment of null to the reference in your code. This is famously known as Null Object Pattern. But saying that the null assignment should itself be compiler error, then I would say, since an Enum is anyways compiled to a Class, so it would be perfectly valid to use null to represent non-existence of an instance.

One pitfall of allowing null though is with the usage of enum in switch-case. The below code will throw NPE:

public class Demo {
    enum Color {
        WHITE, BLACK;
    }

    public static void main(String[] args) {
        Color color = null;

        switch (color) {    // NPE here
        case WHITE: break;
        case BLACK: break;
        }
    }
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download