In java, What does such enum type compile to?

前端 未结 3 770
执笔经年
执笔经年 2020-12-14 10:35

Below is the code that defines enum type.

enum Company{
    EBAY(30), PAYPAL(10), GOOGLE(15), YAHOO(20), ATT(25);
    private int value;

    private Company         


        
3条回答
  •  一个人的身影
    2020-12-14 11:08

    Almost, your second snippet does represent well what is internally generated by the compiler (bytecode) however, it is not exactly the same.

    A compiled enumeration will contains the ACC_ENUM flag which indicates that this class or its superclass is declared as an enumerated type and will be treated as such by the JVM.

    Your second snippet would not (supposing it would compile) include this flag in the bytecode :


    ENUM

    final class Company extends java.lang.Enum
          minor version: 0
          major version: 52
          flags: ACC_FINAL, ACC_SUPER, ACC_ENUM
    

    CLASS

    final class Company
      minor version: 0
      major version: 52
      flags: ACC_FINAL, ACC_SUPER
    

    As for the rest of your logic (still supposing it would compile) it is right. Internally, an enumeration will be represented as a final class which extends java.lang.Enum. However, note that you can't directly extends java.lang.Enum yourself as this stuff is done by the compiler when creating an enumeration and would result in compilation error if you try to do it yourself.

提交回复
热议问题