Java Program Without Making Class



Is it possible to create and run a Java program without any class? The answer is Yes. The trick is to use an enum instead of a Class.

Enums are similar to classes, but instead of using the class keyword, we use enum to define them. An enum is used to represent a public static constant. It can have a static main method as well. 

Steps to write Java program without making class

Following are the steps to write a Java program without making class ?

  • We will start by defining an enum instead of a class. An enum typically represents constants, but it can also include methods.
  • Define the constants and add constants inside the enum.
  • Inside the enum, define the main() method as you would in a class. This is where the program execution starts.
  • Print enum values and use the toString() method to print the enum values.
  • Since the program has a main() method, you can run it directly without a class.

Java program without making class

Below is the Java program without making class ?

public enum Tester {
   C, Java, PHP;
   public static void main(String[] args) {
      System.out.println("Programming in " + Tester.C.toString());
      System.out.println("Programming in " + Tester.Java.toString());
      System.out.println("Programming in " + Tester.PHP.toString());
   }
}

Output

Programming in C
Programming in Java
Programming in PHP

Code Explanation

In the above example, the enum Tester defines three constants: C, Java, and PHP. The main() method prints these constants by calling the toString() method on each one. Even though it's an enum, Java allows the program to run without any issues because the main() method is included within the enum, effectively replacing the need for a class.

Updated on: 2024-10-16T16:29:26+05:30

988 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements