This post will examine the validity of the statement that “Every Java program must have at least one class.” and explore the possibility of writing a Java program without using a class.

1. Using Enum

To write any valid Java program, we need it to be inside a class body. That is one of the main principles of Object-oriented programming languages that Java strictly follows; its Encapsulation pertaining to data security. But instead of using a class, we can switch to enum. An enum is a special type of class that represents a set of constants. We can declare a main method inside an enum and invoke it like any other Java problem. For example, here is a valid Java code that uses an enum instead of a class:

Download  Run Code

2. Using Interface

Another option to write a Java program without using a class is to use an interface instead of a class. An interface is a type that defines a set of abstract methods that can be implemented by classes or other interfaces. Since Java 8, we can also define static methods in an interface. We can declare a main method inside an interface and invoke it normally. For example, the following is a valid Java code that uses an interface instead of a class:

Download  Run Code

 
However, both enum and interface are actually classes internally. They are just special kinds of classes that have some restrictions and features. Therefore, no matter what we write, it has to be inside a class body. The two main reasons behind this are encapsulation (discussed earlier) and as every class automatically inherits Object and String classes, and those are needed to load the main() method and perform any further operations thenceforth.

The purpose of these examples is to show that we can write a Java program without explicitly creating a class. But in reality, every Java program requires the presence of at least one class, because all code in Java is inside classes. So, we can conclude that a class is essential in Java. This concludes our discussion on how to write a Java program without using a class.