0

I had seen a video where, main() can be run with in an enum. I am trying to do the same but it's not working.

Here is my code

public enum EnumMain {                             
   ABC, XYZ;                                       
   public static void main(String[] args) {        
     System.out.print("MIAN");                     
   }                                               
}

Output (The code compiles fine)
Error: Could not find or load main class EnumMain

I think this has something to do with the Java version, may be in Java 8, they are not allowing to run main() method from enum anymore.

PS I am compiling and running the file from windows command prompt.

Note If I change the enum to class then it runs fine (I don't have any classpath issues)

Soumitri Pattnaik
  • 3,246
  • 4
  • 24
  • 42
  • 1
    What's the package of your class and from which folder do you execute your program? – dunni Jun 05 '16 at 08:58
  • @dunni there is no package, I am just creating a .Java file and compiling, running it from command prompt. – Soumitri Pattnaik Jun 05 '16 at 09:06
  • 1
    What's the exact command which you use to execute it? – dunni Jun 05 '16 at 09:16
  • There is nothing special about enums and main method. Change your enum to regular class and you'll see you still can't run the main, because you have class path issues. – Bohemian Jun 05 '16 at 10:51
  • @Bohemian I can run the class if I change the enum to class, it's sad that you marked it as duplicate, without knowing the situation rofl – Soumitri Pattnaik Jun 05 '16 at 11:15
  • @SoumitriPattnaik I can run your code OK. The problem your have has nothing to do with it being an enum. – Bohemian Jun 05 '16 at 16:57
  • See… [it works](http://ideone.com/9BOrQA). – Holger Jun 06 '16 at 12:16
  • @Holger yes, but in my machine it does not, I can run main in a class, I don't know what is the problem – Soumitri Pattnaik Jun 06 '16 at 15:55
  • We don’t have any information about your machine except what you have written in your question (in other words, nothing). It’s supposed to work, it does work on our machines, it works in Java 7 and Java 8, so whatever your problem is, it’s not described in your question… – Holger Jun 06 '16 at 16:56

2 Answers2

1

You can run main within enum.

public enum TestEnumMain{
    val1, val2;
    public static void main(String[] args)
    {
        System.out.println("Hello");
    }
}

Problem would be with you your path variables. Make sure they are configured right. Refer this thread for setting path variables propertly.

Community
  • 1
  • 1
Jaydev
  • 1,794
  • 20
  • 37
0

No, I have run your code on Java 8 and it is perfect. It runs to give output MIAN. I think the problem lies in classpath or in your IDE. You might try after cleaning the project.

Sanjeev Saha
  • 2,632
  • 1
  • 12
  • 19