3

If Enums are an answer for getting rid of compile time constants , why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums ? Those methods can never change the state of the Enum instances or can they ? If they are allowed to change the state , then the invariant of an Enum type ie some type that exports a few constants will break IMHO.

4

3 回答 3

3

Java enums are really just classes with some special treatment by the compiler and runtime. So yes, method calls on an enum instance can certainly change its state. I'm not sure what you mean with "then the invariant of an Enum type ie some type that exports a few constants will break".

Who says enums can only be a bunch of constants? The essence of an enum type is that you have a predefined fixed number of instances which you can refer to by name - and Java enums implement that. But why would a language not be allowed to have enums that are more powerful than that?

If you don't want the extra power, nobody forces you to use it. You can have Java enums without fields or methods, and they'll behave pretty much exactly like C enums.

于 2012-08-02T09:17:03.553 回答
1

Enums are compile-time constants, but their members aren't. It's usually not a good idea to change enum members at runtime, but it is possible. For this reason, you can't use an enum's members where compile-time constants are called for (e.g. in annotation parameters).

Hardly anything in Java is really a constant when you go try hard to mess things up. E.g. a String constant contains a char array. Arrays are not immutable. Here's an example of the mess you can make using inlined String constants:

public static void main(final String[] args) throws Exception {
    final Field valueField = String.class.getDeclaredField("value");
    valueField.setAccessible(true);
    System.arraycopy("frog".toCharArray(), 0,
        (char[]) valueField.get(Boolean.TRUE.toString()), 0, 4);
    System.out.println(Boolean.parseBoolean("frog")); // true
    System.out.println(Boolean.parseBoolean("true")); // false
}

So, Java constants in most cases are just constants as long as your application is well-behaved.

于 2012-08-02T09:56:33.943 回答
0

why did the language designers provide facility to let arbitrary methods and fields and implement arbitrary interfaces on Enums

Reasons are to allow replacing switch-statements with polymorphism and generally make programs more Object Oriented by allowing to define methods on the data.

Search for "type-safe enum pattern". Java Enums are an implementation of this design pattern on language level.

于 2012-08-02T09:17:13.033 回答