為什麼主方法必須在 Java 類中?
主方法是 Java 中執行的入口點。當我們執行一個類時,JVM 搜尋主方法並逐行執行其內容。
如果您觀察以下示例,可以編譯此程式,但如果您嘗試執行它,您將收到一條錯誤訊息,提示“找不到主方法”。
示例
abstract class SuperTest { public abstract void sample(); public abstract void demo(); } public class Example extends SuperTest{ public void sample(){ System.out.println("sample method of the Example class"); } public void demo(){ System.out.println("demo method of the Example class"); } }
輸出
C:\Sample>javac Example.java C:\Sample>java Example Error: Main method not found in class Example, please define the main method as: public static void main(String[] args) or a JavaFX application class must extend javafx.application.Application
廣告