Java high-tech-enumeration

Source: Internet
Author: User

1. What is Enumeration

Enumeration is a new feature added after jdk1.5

To use enumerations to specify a new type, the value of this type must be the value I set. If not, the compiler will make an error, and the benefit is that it will be judged at compile time.

2. The implementation principle of common class simulation enumeration

  

 PackageCom.java.javaenhance1;/*** Using ordinary Java classes to implement the principle of enumeration * This class can only define a few values, this value is not a normal basic type of value, but an object *@authorAdministrator **/ Public classWeekDay {PrivateWeekDay () {} Public Final StaticWeekDay SUN =NewWeekDay ();  Public Final StaticWeekDay MON =NewWeekDay ();  PublicWeekDay NextDay () {if( This==SUN) {            returnMON; } Else {            returnSUN; }    }     PublicString toString () {return  This= = SUN? "SUN": "MON"; }}
 Package Com.java.javaenhance1;  Public class enumtest {    publicstaticvoid  main (string[] args) {        =  Weekday.sun;         // MON        System.out.println (Weekday.tostring ());  // SUN     }}

It is also possible to implement NextDay () in a way that uses abstract methods to escape a large number of if.else statements into separate classes.

 PackageCom.java.javaenhance1;/*** Using ordinary Java classes to implement the principle of enumeration * This class can only define a few values, this value is not a normal basic type of value, but an object *@authorAdministrator **/ Public Abstract classWeekDay {PrivateWeekDay () {}//with a {} representing an anonymous subclass     Public Final StaticWeekDay SUN =NewWeekDay () {@Override PublicWeekDay NextDay () {returnMON;    }    };  Public Final StaticWeekDay MON =NewWeekDay () {@Override PublicWeekDay NextDay () {returnSUN;    }    }; //You can also use abstract classes to implement the NextDay () in their own way .    /*Public WeekDay NextDay () {if (this = = SUN) {return MON;        } else {return SUN; }    }*/    //NextDay have sub-categories to complete     Public AbstractWeekDay nextday ();  PublicString toString () {return  This= = SUN? "SUN": "MON"; }}

Basic application of enumeration of 3.JAVA5

 PackageCom.java.javaenhance1; Public classEnumtest { Public Static voidMain (string[] args) {  WeekDay weekDay2  = Weekday.fri; System.out.println (WeekDay2);         // fri enumeration itself implements ToString ()  System.out.println (Weekday2.name ()); //        fri   System.out.println (Weekday2.ordinal ()); // 5 element, the first one starting from 0  //         System.out.println (weekday.valueof ("SUN")); // sun  //         All the elements in the enumeration are loaded into the array and can be used to traverse the  System.out.println (Weekday.values (). length); // 7      }        /*** Enumerations are equivalent to a class, and the elements in the enumeration are equivalent to the instance object that this class is made out of *@authorAdministrator **/     Public enumweekday{Sun,mon,tue,wed,thi,fri,sat}}

4. Implement an enumeration with constructor methods (constructor with parameters)

/**      * Enumerations are equivalent to a class, and the elements in an enumeration are equivalent     to instances of this class @author  Administrator     * *     / Public    enum  weekday{        SUN (1), Mon,tue,wed,thi,fri,sat;  // All other information that is defined must be behind        the element Private WeekDay () {System.out.println ("First");}    // the construction method must be of the        private type Private WeekDay (int day) {System.out.println ("second");}    }

After the enumeration element is followed by a parenthesis, the parameter in () represents which constructor is used to initialize the element, and if not (), the default null parameter constructor is called

5. Implementing an enumeration with abstract methods

There can be 4 access modifiers in front of the inner class, only two of the outer classes, public and default

Enumerations with abstract methods, elements need to implement abstract methods, using red{} anonymous subclasses

RED (30) indicates which construction method is used to construct the instance object

 Public enumtrafficlamp{RED (30) {//implementing an abstract class using an inner class method@Override PublicTrafficlamp Nextlamp () {returnGREEN; }}, GREEN (45) {@Override PublicTrafficlamp Nextlamp () {returnYELLOW; }}, YELLOW (5) {@Override PublicTrafficlamp Nextlamp () {returnRED;        }        };  Public AbstractTrafficlamp Nextlamp (); Private intTime ; PrivateTrafficlamp (intTime) { This. Time =Time ;} }

After compiling, the. class file for the subclass is automatically generated

When an enumeration has only one member, it can be implemented as a single instance.

If you want to write a singleton, you can write an enumeration with only one element.

Java high-tech-enumeration

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.