Open In App

Java Program Without Making Class

Last Updated : 23 Apr, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

In Java, the easiest way to run a program is by creating a class with a main() method. But there is one more interesting thing that is, we can run a Java program without explicitly creating a class, instead, we can use enum. In this article, we are going to discuss how it works.

What is Enum in Java?

In Java, an Enum is a data type that is used to define a group of constants. Enums are automatically public, static, and final. It simply means:

  • They can not be changed, as they are final.
  • We can access them without creating an object of the enum as they are static.
  • We can not extend them.

Note: In Java, Enums are not regular classes, but they are treated like classes, it simply means we can define methods inside them.

Running a Java Program Using Enum

We can create a main() method inside an enum, without creating a full class.

Example: Here, we are creating a simple Enum with a main() method.

Java
// Java program showing 
// how we can have a main() inside an enum
enum Geeks {
    RED, GREEN, BLUE;

    // Main method inside the enum
    public static void main(String[] args) {
        Geeks g = Geeks.RED;
        System.out.println(g);
    }
}


Output:

EnumOutput

Explanation: Here, in the above example, we have created an enum named as Geeks that define three constants that is RED, GREEN and BLUE. After that we have declared a main() method inside the enum, and we all know main() method is the entry point of the program and inside the main method we created a reference variable g and assigned the constant Geeks.RED and then the program prints the values of g, which is RED.

Use Cases of This Technique

The use cases of this technique is listed below:

  • When we need to run a very simple program, this method save time from writing an entire class.
  • We can use this technique to quickly test a concept or idea without writing a lot of boilerplate code.

Limitations

The limitations of enum are listed below:

  • We all know enum behaves like a class, but it does not support all the features of a regular class like creating a new instance or extending them.
  • Enums works well with small programs, but it’s better to use regular classes for better understanding and readability.


Next Article
Article Tags :
Practice Tags :

Similar Reads