How are enums listed at compile time and how are objects created

enum icecream { vanilla(100), strawberry(20); int price; icecream(int i) { price = i; } } 

I'm a little confused about how enumeration objects are created at compile time

I saw some examples where they referred to this as

 public enum Flavor { COFFEE, VANILLA, CHOCOLATE, STRAWBERRY, RUM_RAISIN, PEACH } 

This will convert (at compile time)

 public final class Flavor extends java.lang.Enum { public static final Flavor COFFEE = new Flavor("COFFEE", 0); public static final Flavor VANILLA = new Flavor("VANILLA", 1); // ... } 

Link: http://www.kdgregory.com/index.php?page=java.enum

But how objects are created when I pass the value along with the name, it seems to me that they just look like method calls. Ex vanilla (100) here for vanilla price is 100, but how is it really created? I do not get it at all. Please, help: (

+4
source share
2 answers

vanilla(100), strawberry(20) is just a java5 + notation. It is converted at compile time to the corresponding object creation code:

 public static final icecream vanilla = new icecream(100); public static final icecream strawberry = new icecream(20); 

By the way, the java type should be CamelCased, so icecream should be called icecream .

+1
source

Enumerations are read by the java compiler as constants, but in the end they are implemented like any other objects (that is, they are not special types such as ints / floats / array, but rather a syntax wrapper on top of a pure object oriented language). Thus, enums have constructors that you can override, so your static enums have more than just a name. This can be very useful, for example, if you want your listed values ​​to have multiple fields.

For example, I might have an Animal enumeration, where each animal has a name, as well as several legs:

 public enum Animal{ Dog(4), Baboon(2); public int legs; private Animal(int legs) { legs=legs; } } 

However, in the absence of such an override, the compiler generates default enumeration objects, which are essentially what you inserted.

+1
source

Source: https://habr.com/ru/post/1387802/


All Articles