Enum class
1 PackageCom.yeepay.sxf.euma;2 /**3 * Enumeration When defining variables, the last enumeration to add;4 * Enumeration of custom variables5 * Enumeration of custom methods6 * How to write weights7 * @authorSXF8 *9 */Ten Public enumColor { One //enumeration constants. At the end of the constant, you need to add; ARed ("Red", 1), -Green ("Greens", 2), -BLANK ("White", 3), theYello ("Yellow", 4); - - //member Variables - PrivateString str; + Private intindex; - + //Construction Method A PrivateColor (String str,intindex) { at This. str=str; - This. index=index; - } - //using enumerations to Judge - Public Static Booleancomper (color color) { - if(color==RED) { in return true; - } to return false; + } - the //data A value that gets an enumeration * Public StaticColor Getindextocolor (intindex) { $ for(Color color:Color.values ()) {Panax Notoginseng if(color.index==index) { - returncolor; the } + } A return NULL; the } + - //override Method $ @Override $ PublicString toString () { - return This. index+ "---" + This. str; - } the - //Set Get MethodWuyi PublicString getstr () { the returnstr; - } Wu - Public voidsetstr (String str) { About This. str =str; $ } - - Public intGetIndex () { - returnindex; A } + the Public voidSetindex (intindex) { - This. index =index; $ } the the the the - in}
View Code
Test class
1 PackageCom.yeepay.sxf.euma;2 3 4 Public classTest {5 Public Static voidMain (string[] args) {6 test2 ();7 }8 9 Ten Public Static voidtest2 () { One //using enumerations directly A Booleanflag=Color.comper (color.red); -System.out.println ("==> directly using enumerations" +flag); - the //gets the value in an enumeration - intindex=Color.BLANK.getIndex (); -String str=Color.BLANK.getStr (); -System.out.println ("Get value in enumeration ==>" +index); +System.out.println ("Get value in enumeration ==>" +str); - + //printing enumerations, overriding methods AString astring=Color.RED.toString (); atSYSTEM.OUT.PRINTLN ("Print values in enumeration ==>" +astring); - - //calling methods in enumerations -Color Color=color.getindextocolor (4); -System.out.println ("Invoke method ==> in enumeration" +color.getstr ()); - in - to } +}
View Code
Print results
==>true that use enumerations directly
Gets the value in the enumeration ==>3
Gets the value in the enumeration ==> white
Print the values in the enumeration ==>1---red
Call the method in the enumeration ==> yellow
Simple application of Enumerations (ii)