Java core classes - enum class

In Java, we can define constants by static final. Such as customized Monday to Sunday:

public  class weekday {
     public  static  final  int SUN = 0 ;
    public  static  final  int MON = 1 ;
    public  static  final  int TEU = 2 ;
    public  static  final  int WED = 3 ;
    public  static  final  int THU = 4 ;
    public  static  final  int FRI = 5 ;
    public  static  final  int SAT = 6 ; 
}

When using constants, so to quote:

if (day == Weekday.SAT || day == Weekday.SUN) {}

Of course, the constant may be defined as a string type.

Whether or int constants String constants, when using these constants to represent a set of enumeration,
there is a serious problem is that the compiler can not check each worth reasonable. such as:

if (weekday == 6 || weekday == 7) {
    if (tasks == weekday.MON) {
        // TODO    
    }
}

Code above two problems exist:
(. 1) to give WEEKDAY defined constants in the range of 0-6, does not contain 7, the compiler can not the detected value is not in the enumeration int
(2) remains constant may be defined by comparison to other variables, but its purpose is not to enumerate the week

In order to allow the compiler to automatically checks a value set in the enumeration and the enumeration of different applications require different types of markers:

enum Weekday {
    SUN,MON,TUE,WED,THU,FRI,SAT;
}

public class catchExample2 {
    public static void main(String[] args) throws Exception {
        Weekday day = Weekday.SUN;
        if (day == Weekday.SAT || day == Weekday.SUN) {
            System.out.println("At home");
        } else {
            System.out.println("At office");
        }
    }
}

The enumeration class is achieved by keyword enum, we only need one name listed enumeration constants.
Int constants defined and compared using enum defined enumeration has the following advantages:
  (1) enum constant itself with the type of information that Weekday.SUN type Weekday, the compiler will automatically check the type of error.
  (2) is not possible references to non-enumeration value, because they can not compile.
  (3) different types of enumeration can not be compared with each other or assignment as incompatible type.
This enables the compiler automatically checks all possible potential errors at compile time.

Enum defined using enumeration is a reference type.
Earlier we talked about, the type of comparative references to the use of equals () method, if you use ==, which compares two references type of variable is the same object.
Therefore, the type of comparative reference, always use equals () method, but enum type can be an exception.
Since each constant enum type in only a single instance of the JVM, it can be used directly == comparison.

enum enumeration class definition, and the class what is the difference?
enum is that a class, only to be individually defined. The main differences are the following:
  (1) the definition of enum type is always inherited from java.lang.Enum, and can not be inherited.
  (2) defines only an example of the enum, enum objects can not be created by the new operator.
  Each instance (3) are defined by reference to a unique instance of the type
  (4) enum type may be used for the switch statement.

For example, we define the color categories:

public enum Color {
    RED, GREEN, BLUE;
}

The class compiler is probably this:

public  Final  class Color the extends the Enum { // inherited from Enum, class labeled Final
     // each instance are globally unique: 
    public  static  Final Color = RED new new Color ();
     public  static  Final Color GREEN = new new Color ();
     public  static  Final Color BLUE = new Color ();
     // Private constructors, can not ensure that the external call the new operator: 
    Private Color () {} 
}

So, compiled enum class and common class does not make any difference.
But we ourselves can not, by definition, the general class as defined in the enum keyword, which is Java syntax rules.

Because enum is a class, the value of each class are enumerated example, therefore, there are some examples of these methods:
name (): returns the constant name
  String Weekday.SUN.name S = ();
ordianl (): Returns the defined constant sequence, starting from 0 technology.
  int n = Weekday.MON.ordinal ();
changing the order of enumeration constants defined will lead ORDINAL () return value.

 

Enumeration created above still exists a problem if we are not careful to modify the order of enumeration,
the return of ordinal value it represents will be modified.
Because we can optimize a little bit, to add a field for each enumeration constants:

package com.imooc.iexecption;

enum Weekday {
    SUN(0), MON(1),TUE(2),WED(3),THU(4),FRI(5),SAT(6);

    public final int dayValue;

    private Weekday(int dayValue) {
        this.dayValue = dayValue;
    }
}

public class catchExample2 {
    public static void main(String[] args) throws Exception {
        Weekday day = Weekday.SUN;
        if (day.dayValue == 6 || day.dayValue == 0) {
            System.out.println("At home");
        } else {
            System.out.println("At office");
        }
    }
}

In this way, we do not have too much attention to the issue of the order.
By default, the enumeration constant call toString () returns, and name () as a string,
however, toString () may be overwritten, and name are not, we can add to the weekday toString () method.

Package com.imooc.iexecption; 

enum Weekday { 
    the SUN ( 0, "Sunday" ), 
    the MON ( . 1, "Monday" ), 
    the TUE ( 2, "Tuesday" ), 
    WEDs ( . 3, "Wednesday" ), 
    the THU ( . 4 , "Thursday" ), 
    the FRI ( . 5, "Friday" ), 
    the SAT ( . 6, "Saturday" ); 

    public  Final  int dayValue;
     Private  Final String chinese; 

    Private Weekday ( int dayValue, chinese String) {
         the this .dayValue = dayValue;
         this.chinese = chinese;
    }
    @Override  //不允许被覆写,也可以直接调用name()
    public String toString() {
        return this.chinese;
    }
}

public class catchExample2 {
    public static void main(String[] args) throws Exception {
        Weekday day = Weekday.SUN;
        if (day.dayValue == 6 || day.dayValue == 0) {
            System.out.println("Today is " + day + " At home");
        } else {
            System.out.println("Today is" + day + "At office");
        }
    }
}

The purpose override toString () in a more readable output.

Enumeration can be used in a switch statement. For there is born because enumeration type information and limited enumeration constants,
so the ratio int, String type is more suitable for use in a switch statement.

package com.imooc.iexecption;

enum Weekday {
    SUN, MON, TUE, WED, THU, FRI, SAT;
}

public class catchExample2 {
    public static void main(String[] args) throws Exception {
        Weekday day = Weekday.SUN;
        switch (day) {
            case SUN:
            case MON:
            case THU:
                System.out.println("Today is " + day + " At home");
                break;
            case WED:
            case TUE:
                System.out.println("Today is " + day + " At office");
                break;
            case FRI:
            case SAT:
            default:
                throw new RuntimeException("cannot process" + day);
        }
    }
}

  When coupled with automatic error default statement, you can write a leak enumeration constants.

Guess you like

Origin www.cnblogs.com/yangmingxianshen/p/12501447.html