The answer is no, the main() method must be public, and the main() method cannot be defined as private and protected, nor without access modifiers.
This is to allow the JVM to access the main() method. If you do not define the main() method as public, although the compilation will succeed, you will get a runtime error because the main method cannot be found.
(1) Now to verify, first change public to private, as follows:
package com.magic.main;
public class MainDemo {
private static void main(String[] args) {
System.out.println("Hello World");
}
}
Try running the program and get the following results:
错误: 在类 com.magic.main.MainDemo 中找不到 main 方法, 请将 main 方法定义为:
public static void main(String[] args)
否则 JavaFX 应用程序类必须扩展javafx.application.Application
(2) Change public to protected, as follows:
package com.magic.main;
public class MainDemo {
protected static void main(String[] args) {
System.out.println("Hello World");
}
}
Try running the program and get the following results:
错误: 在类 com.magic.main.MainDemo 中找不到 main 方法, 请将 main 方法定义为:
public static void main(String[] args)
否则 JavaFX 应用程序类必须扩展javafx.application.Application
(3) Remove the public modifier
package com.magic.main;
public class MainDemo {
static void main(String[] args) {
System.out.println("Hello World");
}
}
Try running the program and get the following results:
错误: 在类 com.magic.main.MainDemo 中找不到 main 方法, 请将 main 方法定义为:
public static void main(String[] args)
否则 JavaFX 应用程序类必须扩展javafx.application.Application
It can be concluded from the above that the main() method must be decorated with public, so the question is: Can the main() method be declared as a non-static method?
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.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。