Why are constants in Java the way they are?
I have read about Java enums and use them regularly. However, I don't understand why e.g JFrame.EXIT_ON_CLOS开发者_开发问答E
returns an int
.
Considering http://download.oracle.com/javase/1.5.0/docs/guide/language/enums.html;
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
public static final int SEASON_SUMMER = 2;
public static final int SEASON_FALL = 3;
Not typesafe - Since a season is just an int you can pass in any other int value where a season is required, or add two seasons together (which makes no sense).
JFrame.EXIT_ON_CLOSE
returns 3, while JFrame.HIDE_ON_CLOSE
returns 1, which means three of the latter equals the first.
Why is it implemented this way?
Java didn't have enums until 1.5 - most of these constants were introduced earlier, and if they were changed to enums Sun would've broken a lot of existing code.
Those constants were probably added to the standard library before enums were added to the language. Enums were added in Java 1.5. To maintain backwards compatibility, they left old constants how they were.
Enums are a recent addition to Java. Changing all of the old integer constants to enums would've broken a lot of existing Java code.
The link that you provided says:
In prior releases, the standard way to represent an enumerated type was
the int Enum pattern:
// int Enum Pattern - has severe problems!
public static final int SEASON_WINTER = 0;
public static final int SEASON_SPRING = 1;
etc...
Java Swing (JFrame) was available much earlier.
精彩评论