Does Enum work as a class?

I wrote a test class, and I tried an enum type:

public class EnumTest { enum Car{MERCEDEZ, FERRARI}; public static void main(String[] args) { Car carObj; carObj.run(); } } 

So it seems that I can “declare” the class using enum (because I don't have the Car class in my package), and I put the run() method to find out what happens. After that, I wrote the body of run() , as the IDE advised me, but inside the rename too.

 enum Car { MERCEDEZ, FERRARI; public void run() { } }; 

I think this is very strange, but good. I continued the experiment with Frankenstein and tried to initialize the object with the constructor on the main one.

 enum Car { MERCEDEZ, FERRARI; public void run() { // TODO Auto-generated method stub }; Car(){} }; 

 Car carObj = new Car(); 

And he says that I cannot create an instance of type EnumTest.Car, so my test is finished, but with doubt. Sorry if this seems silly, but I did not find it in my search.

Question: Why can I use the Car 'like' class, but I can not initialize it?

+4
source share
3 answers

You cannot create an enum instance using the new keyword, because the enumeration constructor is always private.

Enum constructors are implicitly closed , as are interface methods that are implicitly public.

Relevant JLS status section:

If the access modifier is not set for the constructor of the normal class, the constructor has default access.

If no access modifier is specified for the enumeration type constructor, the private constructor.

This is a compile-time error if a constructor of the enumeration type (§8.9) public or protected declared.

You just need to think about it this way, the enumeration is basically a set of values , so its constructor must be private, otherwise someone will just instantiate it and create more values , thereby defeating its entire purpose.

Hope this helps.

+5
source

Car you declare is a nested enum .

It is nested in your EnumTest class and bound to its instance.

You cannot initialize an enum in the same way as a class.

You can, however, declare methods associated with an instance of each of your enum , for example, your run method.

+3
source

You make each enumeration an interface:

 enum Car implements Runnable { MERCEDEZ { @Override public void run() { } }, FERRARI { @Override public void run() { } }; }; public static void main(String[] args) { Car carObj = Car.MERCEDEZ; carObj.run(); } 
0
source

All Articles