Does every program in Java need a class?
•
Java
Is this always the case?
Solution
Yes, you need at least one class to have a program, but no, you don't need any method (contrary to some other answers)
The reason you need a class is because in Java, all the code is in the class So to have any code, you need a class However, the code does not necessarily need to be in a method It can also be in the initializer Therefore, this is a complete Java program without methods:
class LookMaNoMethods { static { System.out.println("Hello,world!"); System.exit(0); } }
This gives
$javac LookMaNoMethods.java $java LookMaNoMethods Hello,world! $
Edit: the code from Java 7 has only static blocks without main method, and will not produce any output The main method is now mandatory Code without the main method can be compiled successfully
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码