Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In java, What does such enum type compile to?

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(int value){
        super(this.name()); 
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

that gets internally compiled to,

final class Company extends Enum<Company>{
    public final static Company EBAY = new Company(30);
    public final static Company PAYPAL = new Company(10);
    public final static Company GOOGLE = new Company(15);
    public final static Company YAHOO = new Company(20);
    public final static Company ATT = new Company(25);

    private int value;

    private Company(int value){
        super(this.name(),Enum.valueOf(Company.class, this.name()));
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}

Is my understanding correct?

like image 460
overexchange Avatar asked Jun 25 '15 01:06

overexchange


People also ask

What do enums compile to?

Java enums are syntactic sugar. Java compiler compiles an enum class to a simple Java class extending java.

What does enum do in Java?

An enum type is a special data type that enables for a variable to be a set of predefined constants. The variable must be equal to one of the values that have been predefined for it. Common examples include compass directions (values of NORTH, SOUTH, EAST, and WEST) and the days of the week.

What does enum stand for Java?

An enum is a special "class" that represents a group of constants (unchangeable variables, like final variables). To create an enum , use the enum keyword (instead of class or interface), and separate the constants with a comma.

What enum is used for?

Enumeration or Enum in C is a special kind of data type defined by the user. It consists of constant integrals or integers that are given names by a user. The use of enum in C to name the integer values makes the entire program easy to learn, understand, and maintain by the same or even different programmer.


1 Answers

Functionally, yes. Literally no (you can't explicitly sub-class Enum for one thing). enum(s) have a toString. And your enum isn't valid code (you can't call super()) and getValue needs a return type.

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

    private Company(int value){
        this.value = value;
    }

    public int getValue(){
        return value;
    }
}
like image 149
Elliott Frisch Avatar answered Sep 29 '22 01:09

Elliott Frisch