Java Foundation Strengthening-JDK1.5 new features-enumeration __java

Source: Internet
Author: User
Tags constant definition

Java JDK1.5 New features – Enumerations

I. Enumeration definition

Definition: An enumeration is a special class defined using an enum declaration, but it does not inherit from the Java.lang.Object class, which inherits from the Java.lang.enum<e> class, which is all Java The common base class of the language enumeration type, where the Java.lang.Enum class implements the Java.lang.Serializable and java.lang.Comparable two interfaces.

Two. features of the enumeration

1. Since the enumeration is a special class, it can also have a construction method, except that the constructor method in the enumeration is private and is used only when an enumeration value is created internally (or an object of this enumeration type), and there is absolutely no public constructor allowed. This guarantees that the external code cannot construct an instance of the enumeration class, and that the constructor can have multiple, which is the corresponding value to initialize. (because we know that the enumeration value is the public static final constant.) However, the enumeration class's methods and data fields can be allowed externally.

2. each element (enumerated value) is public and static, final decorated, which is the constant definition method that we often use, so the generic enumeration value names are all in uppercase letters, and can be called directly with enumerated type names. As with static properties and methods in normal classes, you can use the class name. Static members are called directly.

3. enumeration values in an enumeration can only be given at declaration time, after the compilation period or the runtime is not like the normal class as the new object, so the enumerated elements are stable and fixed, and the elements are limited.

4. General Swtich can only use Byte, short, int, char four basic data types as values, but enumerations can also be used as the value of a switch statement.

5. when defining an abstract method in an enumeration class, you do not need to display an enumeration class as an abstract class using the abstract keyword, but because an enumeration class needs to display the creation of an enumeration value rather than as a parent class, you must provide an implementation for an abstract method when defining each enumeration value, otherwise, It is often convenient to use an anonymous inner class implementation internally.

6. enumeration classes are defined through the enum keyword, and the enumeration class is a special class with each element being an instance object of the class.

7. If the caller wants to print the information for the elements in the enumeration class, the ToString method must be defined by the person writing the class.

8. The enumeration class is a class, and is a final class that cannot be inherited, where the elements are class static constants.

9. enumerations are equivalent to a class, which can also define construction methods, member variables, common methods, and abstract methods.

The enumeration elements must be in the first part of the enumeration body, and a semicolon is separated from the other members after enumerating the list of elements. The compiler reports an error by placing the member methods or variables in the enumeration in front of the enumeration elements.

three. Why do you want to use enumerations?

1. If there is a variable now, to assign a value to it, but the value of this variable can only be one of several fixed values, otherwise the compilation is wrong, reducing run-time errors and errors, then use the enumeration, in the enumeration class to define a limited number of enumerated elements to use, This makes it safe and convenient to assign values to variables.

2. Errors are found at compile time, indicating that the values are not compliant, reducing run-time errors.

For example:

A. What is the definition of a variable that defines the week or gender? Suppose to be 1-7 for Monday to Sunday, but someone might write int weekday = 0, or even use a constant method to prevent an unexpected.

B. Enumeration is to make a variable of a type can only be one of several fixed values, otherwise, the compiler will error. Enumerations allow the compiler to control the illegal values that are filled out in the source program at compile time, and common variables cannot be achieved in the development phase.

Practice Code 1:

	/ 
	 * * Using the common class to implement the enumeration function, define a weekday class to simulate the enumeration function.  
	    1, Private construction Method 
	    2, each element with a public static member variable 
	    to represent 3, can have several public methods or abstract methods. Using abstract methods to define NextDay, a large number of if.else statements are transferred to a separate class. 
	 
	* *  
	  
	package Cn.itheima;  
	  
	Public abstract class Weekday {  
	    private weekday () {} public  
	  
	    final static weekday sun=new weekday () {public  
	        We Ekday NextDay () {return  
	            MON;  
	        }  
	    };  	      
	    Public final static weekday Mon=new weekday () {public  
	        weekday NextDay () {return  
	            SUN;  
	        }  
	    };  
	      
	    Public abstract weekday NextDay ();  
	  
	    Public String toString () {return  
	        This==sun? SUM ":" MON ";  
	    }  
	}  

Four. Application of enumeration

1. Static methods in enumerations

A. valueof (Stringe);

Converts the given string to the corresponding element or object in the enumeration.

B. values ();

Returns an array that contains all the enumeration elements in the enumeration class.

2. Non-static methods

A. stringtostring (); Returns the name of the enumeration

B. intordinal (); Returns the order of the enumeration values in the enumeration class, sorted in the order defined.

C. Classgetclass (); get the corresponding class name

D. Stringname (); Returns the name of this enumeration constant, declared in its enumeration declaration.

Practice Code 2:

 public class Weekdaytest {public static void main (string[] args) {weekday[] days = Weekday.values ();
		               for (weekday day:days) {SYSTEM.OUT.PRINTLN ("Today is:" +day);
		               System.out.println ("Tomorrow is:" +day.nextday ());
		         System.out.println ("==================="); 
			    	}//define an internal enum class enum weekday {//Each element uses an anonymous inner class method to implement an abstract method that returns the day of the day of the week MON {@Override
			    	Public weekday NextDay () {return TUE; }, TUE {@Override public weekday NextDay () {return W
			    	ED; }, WED {@Override public weekday NextDay () {return THU
			    	;
		    		}, THU {@Override public weekday NextDay () {return FRI; }}, FRI {@Override public weekday NextDay () {return SAT;
		    	    	The SAT {@Override public weekday nextday () {
		    	    return SUN; }, SUN {@Override public weekday NextDay () {RE
		    	    Turn MON;
		       }
		       };
	Define an abstract method to represent the day of the week as public abstract weekday nextday ();
 }
}

Practice Code 3:

 package Cn.itheima;  
	        public class Enumdemo {public static void main (string[] args) {weekday weekday=weekday.mon; SYSTEM.OUT.PRINTLN (weekday);//output enumerated constant name System.out.println (Weekday.name ());//Output Object name System.out.printl N (Weekday.getclass ());//Output corresponding class System.out.println (weekday.tostring ());//Output enumerated object name System.out.println (we Ekday.ordinal ())//Output This object in the order of the enumerated constants System.out.println (weekday.valueof ("WED"));//Convert the string to an enumerated constant System.out . println (Weekday.values (). length);//get so enumerated elements and print their length}//define Enum internal class public enum weekday{SUN (  
	        1), the mon,tue,wed,thi,fri,sat;//semicolon is optional, but the semicolon cannot be saved if there are methods or other members below.  
	  
	        And when there are other methods, you must be under these enumerated variables.  
	        Non-parametric constructor private weekday () {SYSTEM.OUT.PRINTLN ("a");  
	        }///constructor private weekday (int day) {System.out.println ("Second") with parameters; }  
	    }  
	}  

Practice Code 4:

public class Enumtest {public  
	    enum trafficlamp{  
	        RED {public  
	            trafficlamp Nextlamp () {return  
	                GREEN;  
	            }  
	        ,  
	        GREEN {public  
	            trafficlamp Nextlamp () {return  
                yellow  
	            }  
        },  
        yellow (5) { Public  
	            Trafficlamp Nextlamp () {return  
	                RED;  
	            }  
	        };  
	        private int time;  
	        Constructor  
	        private Trafficlamp (int time) {  
	            This.time=time}  
	        Abstract method Public  
	        abstract Trafficlamp nextlamp ();  
	    }       
	    public static void Main (string[] args)
		{
	    	trafficlamp[] tls = Trafficlamp.values ();
	    	for (Trafficlamp Tl:tls)
	    	{
	    		   System.out.println ("The currently lit Light is:" +TL);
	    		   System.out.println ("The current light duration is:" +tl.time);
	    		 System.out.println ("Next lit wait is:" +tl.nextlamp ());
	    	}
		





Related Article

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.