Is it possible to write a Java program without using a class?
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:
|
1 2 3 4 5 6 7 |
enum Main { Main; public static void main(String[] args) { System.out.println("Hello World"); } } |
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:
|
1 2 3 4 5 |
interface Main { static void main(String[] args) { System.out.println("Hello World"); } } |
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.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)