James Ko
James Ko

Reputation: 34569

Can you create a not-defined enum value in Java, like in .NET?

I don't have that much experience in Java compared to .NET. In .NET, enums are treated as thin wrappers over integers, so you can easily create an enum value that is unnamed. For 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 it possible to do the same thing in Java?

edit: This seems to be the case from the fact that this 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 about a missing return statement
}

Upvotes: 4

Views: 422

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726809

Java implements enums differently from C#: rather than making them a thin wrapper over ints, it makes them thin wrappers around objects, a compiler-aided improvement on the type-safe enum pattern.

Compiler ensures that it is not possible to create an instance of an enum that is not included in the type.

There are advantages and disadvantages to each approach. C# stays closer to C and C++ enums, which behave like collections of named numeric constants. This makes it possible to create [Flag] enumerations - something that would not be possible with Java enums.

On the other hand, Java enums are fully working objects, complete with methods of their own, and an ability to implement interfaces. Methods can be added to C# enums as extensions, but it is not possible to implement an interface.

Upvotes: 4

Related Questions