The answer is no, the main() method must be declared static so that the JVM can call the main() method without first instantiating its class.

Because main is the entry method of the program, when the program runs, the first method executed is the main() method. Generally speaking, to execute a method of a class, you must first instantiate an object of the class, and then call the method through the object. However, since main is the entry method of the program, the object has not been instantiated at this time, so when writing the main() method, it is required to call this method without instantiating the object. In view of this, the main() method needs to be defined as public with static.

If you remove the static declaration from the main() method, although the compilation can still be successful, it will cause the program to fail at runtime, such as the following program:

 package com.magic.main;

public class MainDemo {

    public void main(String[] args) {
        System.out.println("Hello World");
    }
    
}

(1) Use the javac MainDemo.java command to compile first, and you will get the MainDemo.class file;

(2) Run the java MainDemo.class command again, and you will see the following error output

 错误: 找不到或无法加载主类 MainDemo.class

As can be seen from the above, if the static declaration of the main() method is removed, although the compilation is successful, it cannot be run!

Similarly, if you remove the public modifier, or modify it to private or protected, it will not work.

For more knowledge points related to Java interviews, you can pay attention to the [Java Interview Manual] applet, which involves Java foundation, multithreading, JVM, Spring, Spring Boot, Spring Cloud, Mybatis, Redis, database, data structure and algorithm.


十方
226 声望433 粉丝