Java enum explanation

Source: Internet
Author: User

Enum

An enum is a concept introduced by jdk1.5. The value of the enum type is actually represented by the object constructed at run time. When defining an enum, the compiler will do something for us by default:

    1. All enum classes inherit the enum (enum default implementation comparable and Serializable interface) by default, so enum classes cannot inherit other classes (Java single inheritance);
    2. All enum classes are final and cannot have sub-classes
    3. All defined enumeration constants that generate public static final constants in the defined enumeration class

Note : Switch uses the equal () method by default when judging whether it is equal

custom enum Types :

 Public enumenumtest{Yahoo ("Www.yaho.com"), Baidu ("Www.baidu.com"), Google ("www.google.com");//Note that if there is a custom method, the last enumeration value is required;    PrivateString name;//The construction method must be private or friendly    Private enumtest(String name) { This. name=name; } PublicStringGetName()    {returnName }    }in the//main function      Public Static void Main(string[] args) {System. out. println (EnumTest.Baidu.getName ()); Output Baidu's website
Enum-related tool classes
enumweekday{Mon,tue,wen}enumenumnetwork{Yahoo, Baidu, Google} Public classTest { Public Static void Main(string[] args) { for(WeekDay day:WeekDay.values ()) {System. out. println (day); }//enumset internal through Bit-vector implementation         for(WeekDay Day:EnumSet.range (Weekday.mon,weekday.wen)) {System. out. println (day); }//Note the difference between ENUMMAP and general map usageEnummap<weekday,enumnetwork> map=NewEnummap<weekday, enumnetwork> (Weekday.class); for(intI=0; I<weekday.values (). length;i++) {map.put (Weekday.values () [I],enumnetwork.values () [i]); } System. out. println (Map.Get(Weekday.mon)); }}

Java enum detailed

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.