c# - Can you create a not-defined enum value in Java, like in .NET? -
i don't have experience in java compared .net. in .net, enums treated thin wrappers on integers, can create enum value unnamed. example:
// c# code public enum colors { red, green, blue } console.writeline(colors.red + " " + colors.green + " " + colors.blue); // red green blue var unknown = (colors)(-1); console.writeline(unknown); // -1
is possible same thing in java?
edit: seems case fact code won't compile:
// java code enum colors { r, g, b } static int f(colors c) { switch (c) { case r: return 1; case g: return 2; case b: return 3; } // compiler complains missing return statement }
java implements enum
s differently c#: rather making them thin wrapper on int
s, makes them thin wrappers around objects, compiler-aided improvement on type-safe enum
pattern.
compiler ensures not possible create instance of enum
not included in type.
there advantages , disadvantages each approach. c# stays closer c , c++ enum
s, behave collections of named numeric constants. makes possible create [flag]
enumerations - not possible java enum
s.
on other hand, java enum
s working objects, complete methods of own, , ability implement interfaces. methods can added c# enum
s extensions, not possible implement interface.
Comments
Post a Comment