2011-04-23 70 views
1

我已閱讀Java枚舉並定期使用它們。不過,我不明白爲什麼e.g JFrame.EXIT_ON_CLOSE返回int爲什麼Java中的常量是他們的方式?

考慮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; 

不是類型安全 - 因爲一個賽季只是你可以在需要一個賽季的任何其他int值傳遞,或添加兩個賽季在一起(這是沒有意義的)一個int。

JFrame.EXIT_ON_CLOSE返回,而JFrame.HIDE_ON_CLOSE返回,這意味着三個後者等於第一。

爲什麼這種方式來實現?

+0

它可能不應該。 – 2011-04-23 19:52:43

回答

13

Java沒有枚舉until 1.5 - 這些常量中的大多數是早些時候推出的,如果它們被更改爲枚舉,Sun將破壞大量現有代碼。

+0

在Swing的其他地方,枚舉「模式」在沒有語言支持的情況下使用。 – 2011-04-23 20:07:54

3

這些常數可能添加到標準庫枚舉被添加到語言之前。枚舉是在Java 1.5中添加的。爲了保持向後兼容性,他們將舊常量保持原樣。

3

枚舉是最近才加入到Java。將所有舊的整型常量改爲枚舉會破壞很多現有的Java代碼。

1

您提供的鏈接說:

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的)是可利用的要早得多。

相關問題