public enum Apple { PIPO(1), BIBO(2), GITO(3); private int price; Apple(int price){ this.price = price; } int getPrice(){ return price; } } public class Test { public static void main(String[] args) { Apple apple1 = Apple.PIPO(2); System.out.println(apple1); } } 

Apple has a defined constructor in enum and I don’t understand why we write the enumeration data to the constructor right in ENUM, and not in another place when creating the object, let's say we do it with classes:

 PIPO(1), BIBO(2) ... // в enum(e), а не вот ниже public class Test { public static void main(String[] args) { Apple apple1 = Apple.PIPO(2); //вот тут System.out.println(apple1); } } 
  • Enum instances are created when the class is loaded by the loader class, you yourself cannot create them - Stranger in the Q 4:47 pm
  • @StrangerintheQ Sorry, did not quite understand, can be more? - user331073 pm
  • These constructors are called automatically when the program starts, you cannot manually create an instance of the enumeration - Stranger in the Q
  • @StrangerintheQ I just like, let's say I did a constructor and a variable in a class and in another class where the Maine method I created an instance of the class and entered parameters there, and then the constructor immediately, the variable here and then passed to the constructor you need the parameters in this example how so? - user331073 pm
  • yes, and what confuses you? predefined parameters? - Stranger in the Q

1 answer 1

I understand that you do not understand the sacred meaning of the need for such a tool as enumeration (enum), I will try to explain.

Your example from the question, with the price of apples, can be a little confusing, because price is variable in some way.

It is better to take for example the color of a traffic light in a game.

 enum Color { RED, GREEN, YELLOW } 

All components of a particular color are constant.

In 99% of cases you do not need to have 2 different classes describing yellow color. In the rgb color scale, for example, the yellow color will be represented by something like (255, 255, 0) .

Accordingly, our enum will have some form:

 enum Color { RED(255, 0, 0), GREEN(0, 255, 0), YELLOW(255, 255, 0); int r; int g; int b; Color(int r, int g, int b){ this.r = r; this.g = g; this.b = b; } .... } 

Instances of our Color enumeration will be created at the time of loading the class, with the ClassLoader and will never be consumed by the GarbageCollector . And you refer to them as a static link.

 Color currentColor = Color.RED; 

Something like that, I hope you have at least become a little clearer =)

  • Thanks, now yes - user331073