我們能在 Java 中定義一個與類名相同的類方法嗎?


可以,在 Java 中定義方法名與類名相同是允許的。不會產生編譯時或執行時錯誤。但根據 Java 的編碼標準不建議這樣做。通常,建構函式名和類名在 Java 中始終相同

例項

線上演示

public class MethodNameTest {
   private String str = "Welcome to TutorialsPoint";
   public void MethodNameTest() { // Declared method name same as the class name
      System.out.println("Both method name and class name are the same");
   }
   public static void main(String args[]) {
      MethodNameTest test = new MethodNameTest();
      System.out.println(test.str);
      System.out.println(test.MethodNameTest());
   }
}

在上面的示例中,我們可以宣告方法名 (MethodNameTest) 與類名相同 (MethodNameTest),它將成功編譯而不產生任何錯誤。

輸出

Welcome to TutorialsPoint
Both method name and class name are the same

更新日期: 2019-07-30

5K+ 瀏覽量

開啟你的 職業生涯

完成課程,獲得認證

開始學習
廣告