首页 文章资讯内容详情

Java 中main修饰符public替换为private会发生什么

2026-06-03 1 花语

当在main方法中使用public修饰符时-

示例

public class Demo{ public static void main(String args[]){ System.out.println("This is a sample only"); } }

输出结果

This is a sample only

名为Demo的类包含publicmain方法。它具有打印输出功能,可以成功地在控制台上编译,执行和打印消息。

当“public”替换为“private”时

示例

public class Demo{ private static void main(String args[]){ System.out.println("This is a sample only"); } }

输出结果

Error: Main method not found in class Demo, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application

名为Demo的类包含private而不是publicmain方法时。该方法无法成功编译,因此出现错误,指出未找到“main”方法,因为由于它是私有的而无法访问。