4

I wrote a test class and I was trying the 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' a class using the enum (because i do not have a class Car in my package), and I put the method run() to see what happens. After that, i wrote the run() body as the IDE adviced me, but inside the enum too.

enum Car {
   MERCEDEZ, FERRARI;

      public void run() {   
      }
   };

I think that it is very weird, but ok. I continued with my Frankenstein experiment and tried to initialize the object with a constructor on main.

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

        };
        Car(){}
    };

Car carObj = new Car();

And it says that I can not instantiate the type EnumTest.Car, so my test is finished, but with doubt. Sorry if it seems to be silly, but i did not find this on my searches.

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

Lupiyo
  • 169
  • 1
  • 10
  • 1
    The constructor for an enum type must be package-private or private access. It automatically creates the constants that are defined at the beginning of the enum body. You cannot invoke an enum constructor yourself. https://docs.oracle.com/javase/tutorial/java/javaOO/enum.html – kosa Aug 12 '15 at 16:05
  • 1
    Your misunderstanding comes from not knowing how references are initialized in Java. `Car carObj;` - this does not initialize anything, no matter if `enum` is class or, well, enum. – Dmitry Zaytsev Aug 12 '15 at 16:05

2 Answers2

3

The Car you declare is a nested enum.

It's nested in your EnumTest class, and bound to its instance.

You cannot initialize an enum the same way you would a class.

You can, however, declare methods bound to the instance of each of your enum, such as your run method.

Mena
  • 47,782
  • 11
  • 87
  • 106
0

You make each enum implement the 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();
}
OldCurmudgeon
  • 64,482
  • 16
  • 119
  • 213