What's going on with the Java enum enumeration?

Source: Internet
Author: User

Java1.5 is not enumerated before, if you want to use an enumeration-like attribute, that is, when you need to use a constant, you can do so by the following code:

Constants in Java are defined as:

Public class Sex2 {

public staticfinalintGIRL = 1;

public staticfinalint boy = 2;

public staticvoid main (string[]args ) {

System. out . println (Sex2. GIRL );

    }

}

But there is a drawback, is not enough intuitive, we print out Sex2. GIRL, See is the number 1. So we have the following improvements:

Improvement One:

Public class Sex3 {

public staticfinal StringGIRL ="GIRL ";

public staticfinal String Boy = "Boy";

public staticvoid main (string[]args) {

System. out . println (Sex3. GIRL );

    }

}

Now it's more intuitive, we print out Sex3. GIRL, you can see is GIRL, meaning is very clear. But again, if I had a way to accept girl or boy as arguments, I couldn't guarantee that someone else would use another string, such as "KID", when calling the method. So we have further improvements:

Improvement Two:

Public class Sex4 {

    public static final Sex4 girl = new Sex4 (

public staticfinal Sex4 Boy =New Sex4 ("GIRL");

Private Stringsex;

Private Sex4 (Stringsex) {

this. Sex = Sex ;

    }

public String toString () {

returnsex;

    }

}

In this way, you can use the SEX4 type to ensure that the gender can be a boy or a girl if you need to use sex elsewhere. For example, a function similar to the following definition:

Public void outsex (Sex4sex) {

System. out . println (sex);

}

But now that's the problem, we're just going to use two constants, but there's no easy way to write so many lines of code (when defining SEX4). The answer is of course there is, in order to simplify our code writing, the Java enum type was born, the following code is equivalent to the above SEX4 definition:

Improvement Three, enum type turned out:

Public enum Sexenum {

GIRL,

boy

}

Oh, my God! I can't believe it, it's so neat! How do you define a place that needs to be used?:

Public void outsex (sexenumsex) {

System. out . println (sex);

}

question : Since there is no enum before Java1.5, then what is the 1.5-something enum? What's the difference between him and a normal class?

I'm telling you, actually, the enum in Java is just a class, and defining an enum is defining a class, which is a testament to Sexenum.class's anti-compilation.

Javap-p Sexenum.class


Compiled from "Sexenum.java"

Public Final class Sexenum extendsjava.lang.enum<sexenum> {

public static final Sexenum GIRL;

public static final Sexenum boy;

private static final sexenum[] $VALUES;

public static sexenum[] values ();

public static Sexenum valueOf (java.lang.String);

Private Sexenum ();

static {};

}

We see that Sexenum is a final modified class that inherits from Java.lang.Enum. We also saw four additional members and a static block of code in the class, in addition to our own definition of girl and boy members. Please note that the construction method is private! As you might have guessed, here's the inheritance, and these members are the compilers that help us Add. These member functions and the JVM bytecode corresponding to the static code block can be seen by anti-compilation:

Javap-c Sexenum.class


Compiled from "Sexenum.java"

Public final class Sexenum extendsjava.lang.enum<sexenum> {

public static final Sexenum GIRL;

public static final Sexenum boy;

public static sexenum[] values ();

Code:

0:getstatic #1//Field $VALUES: [Lsexenum;

3:invokevirtual #2//Method "[Lsexenum;]. Clone: () Ljava/lang/object;

6:checkcast #3//Class "[Lsexenum;"]

9:areturn

public static Sexenum valueOf (java.lang.String);

Code:

0:LDC #4//Class Sexenum

2:aload_0

3:invokestatic #5//methodjava/lang/enum.valueof: (Ljava/lang/class; ljava/lang/string;) Ljava/lang/enum;

6:checkcast #4//Class Sexenum

9:areturn

static {};

Code:

0:new #4//Class Sexenum

3:dup

4:LDC #7//String GIRL

6:iconst_0

7:invokespecial #8//Method "<init>":(ljava/lang/string;i) V

10:putstatic #9//Field girl:lsexenum;

13:new #4//Class Sexenum

16:dup

17:LDC #10//String Boy

19:iconst_1

20:invokespecial #8//Method "<init>":(ljava/lang/string;i) V

23:putstatic #11//Field boy:lsexenum;

26:iconst_2

27:anewarray #4//Class Sexenum

30:dup

31:iconst_0

32:getstatic #9//Field girl:lsexenum;

35:aastore

36:dup

37:iconst_1

38:getstatic #11//Field boy:lsexenum;

41:aastore

42:putstatic #1//Field $VALUES: [Lsexenum;

45:return

}

Obviously, the code that corresponds to the static block of code completes the initialization of Members girl and boy. Long time no See the JVM bytecode, have forgotten, to understand the semantics of the bytecode, please read the Java Virtual Machine manual

Conclusion: By defining an enumeration, you can guarantee where you need to use the enumeration, and the parameter must be a member of the enumeration, while enhancing the readability of the code. Enum is just a syntactic sugar provided to us by the Java language [1] (what is syntactic sugar?) ), which allows us to define constants. What is defined by the enum keyword is actually a class, except that the compiler guarantees that the class inherits from the enum and will automatically add some members to the class.

[1] syntax sugar: is at the compiler level of the Java syntax changes, and did not change the JVM, that is, the structure of bytecode has not changed. Syntax sugar in Java is also: generics, enhanced for, and so on.

A shallow understanding of the individual, welcome reprint, Reprint annotated source http://blog.csdn.net/u014495327/article/details/42043823. by Hoolee.

What's going on with the Java enum 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.