Is it possible to write a Java program without using a class?

Every Java program must have atleast one class.

In this post, we will see if this statement is entirely true or if there is some way which allows us to write a java program without using a class.


 

In order 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 classes, we can switch to enum as shown below:

Download   Run Code

Output:

Hello World

 
This will work fine but an enum is nothing but a class itself. So no matter what we write, it has to be inside a class body. The two main reasons behind this are encapsulation (as covered earlier) and as every class automatically inherits Object and String (from java.lang package) classes and those are needed to load the main() method and perform any further operations thenceforth.

So we can conclude that class is absolutely necessary in Java.

 
Author: Sourav Dutta

 
Thanks for reading.

Please use ideone or C++ Shell or any other online compiler link to post code in comments.
Like us? Please spread the word and help us grow. Happy coding 🙂
 





Leave a Reply

Notify of
avatar
wpDiscuz