Java enumeration examples

Source: Internet
Author: User

Java enumeration examples

We have learned enumeration when learning programming languages. Now let's take a look at the usage of enumeration in java.

The Code is as follows:

Public class test {

Public static void main (String [] args ){

WeekDay w = WeekDay. MON;

System. out. println (w); // you can call the tostring method.

System. out. println (w. ordinal (); // print the objects in the enumeration list.

System. out. println (WeekDay. values (). length); // The total number of enumerated objects.

}

Public enum WeekDay {

SAT, MON, TUE, WED, THU, FRI, SAT,

Private WeekDay (){

System. out. println ("11 ");

}

Private WeekDay (int ){

System. out. println ("");

}

}

}

 

 

First, we define a simple enumeration class WeekDay.

 

Sat, mon... and so on in this class are actually weekday class objects.

 

Note:

 

Enumeration classes also have constructor methods, which must be private;

 

The following code can be used to understand the usage of enumeration types. It should be understood in combination with internal classes.

 

The Code is as follows:

Public enum TrefficLamp {

RED (30) {// The construction method for calling the parameter of the RED light object to be int type,

Public TrefficLamp nextLamp (){

Return GREEN;

}

},

GREEN (20 ){

Public TrefficLamp nextLamp (){

Return YELLOW;

}

},

YELLOW (2 ){

Public TrefficLamp nextLamp (){

Return RED;

}

};

Public abstract TrefficLamp nextLamp ();

Private int time;

Private TrefficLamp (int time ){

This. time = time;

};

}

 

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.