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


this more of design question. (so, no code. post code of creating enum , assigning null if want me it. :)) i've been thinking lot lately can't come 1 reason. enum constants implicitly static , final. enum meant - "i can take value of 1 of constants present in me". why allow enum have null value?. why not implicitly default enum's value enum.default or enum.none?. isn't better approach allowing enum null?

firstly null means non-existence of instance. providing default constant default or none, change meaning. secondly, why need default represent seems non-existent? purpose of null. basically, have initialize , store object, shouldn't exist whatsoever.

btw, it's not language choice. it's on how implement enum. can provide constant default, or unknown in enum, , avoid assignment of null reference in code. famously known null object pattern. saying null assignment should compiler error, say, since enum anyways compiled class, valid use null represent non-existence of instance.

one pitfall of allowing null though usage of enum in switch-case. below code 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;         }     } } 

Comments

Popular posts from this blog

windows - Single EXE to Install Python Standalone Executable for Easy Distribution -

c# - Access objects in UserControl from MainWindow in WPF -

javascript - How to name a jQuery function to make a browser's back button work? -