ÉèΪÊ×Ò³ ¼ÓÈëÊÕ²Ø

TOP

What is the advantage of using enum over static final variable for using constants?
2014-10-30 13:45:04 À´Ô´: ×÷Õß: ¡¾´ó ÖРС¡¿ ä¯ÀÀ:31´Î
Tags£ºWhat the advantage using enum over static final variable for constants

Often, we need a discrete domain of related values, such as to indicate types of things (customer type, transaction type, state, etc.) or for flags. Before Enums, a common technique was to declare the field/member as "int" and use constants (public static final int) to define the specific expected values. The problem is that, while there is type safety (int), there is no "value safety"; since the field is defined int, it can take ANY int value ¨C even values not defined in the constants. You can add validation to methods to ensure the value passed is one of the set of "magic" values (as defined by the constantr to achieve run-time "value safety", but there is nothing that prevents the author of "client" code from trying to send a bad value.
Using Enums, you define a specific class with (effectively) a discrete set of static singletons to represent the complete domain of all possible values for a particular purpose. This provides both compile-time and run-time type-safety and "value safety" ¨C while still being usable in a switch/case statement ¨C and allowing for encapsulation of other useful behaviors such as for printing (override Object.toString) and sorting (implement Comparable.compareTo).
Constants (public static final) are still useful where your code can legitimately accept ANY value of the defined type (e.g. int, double, etc.) but where there are certain "magic" values that are used more often and so you want to define convenient constants for easier reference ¡­ or to help document key literals in your algorithms ¡­ e.g. PI=3.14159 or LINE_SEPARATOR="\n". .


¡¾´ó ÖРС¡¿¡¾´òÓ¡¡¿ ¡¾·±Ìå¡¿¡¾Í¶¸å¡¿¡¾Êղء¿ ¡¾ÍƼö¡¿¡¾¾Ù±¨¡¿¡¾ÆÀÂÛ¡¿ ¡¾¹Ø±Õ¡¿ ¡¾·µ»Ø¶¥²¿¡¿
·ÖÏíµ½: 
ÉÏһƪ£º°¢Àï°Í°Í2013ʵϰÉúÕÐÆ¸±ÊÊÔÌâ ÏÂһƪ£ºJAVAÃæÊÔÌâ½â»óϵÁÐ ¨C µ½µ×´´½¨Á..

ÆÀÂÛ

ÕÊ¡¡¡¡ºÅ: ÃÜÂë: (ÐÂÓû§×¢²á)
Ñé Ö¤ Âë:
±í¡¡¡¡Çé:
ÄÚ¡¡¡¡ÈÝ: