Java 中的建構函式有返回型別嗎?


不,Java 中的建構函式沒有返回型別。

建構函式看起來像方法,但不是。它沒有返回型別,它的名稱與類名相同。它主要用於例項化類的例項變數。

如果程式設計師不編寫建構函式,編譯器會替他編寫一個建構函式。

示例

如果你仔細觀察以下示例中建構函式的宣告,它只包含建構函式的名稱(與類名類似)和引數。它沒有任何返回型別。

public class DemoTest{
   String name;
   int age;
   
   DemoTest(String name, int age){
      this.name = name;
      this.age = age;
      System.out.println("This is the constructor of the demo class");
   }
   public static void main(String args[]){
      Scanner sc = new Scanner(System.in);
      System.out.println("Enter the value of name: ");
      
      String name = sc.nextLine();
      System.out.println("Enter the value of age: ");
      
      int age = sc.nextInt();
      DemoTest obj = new DemoTest(name, age);
      
      System.out.println("Value of the instance variable name: "+name);
      System.out.println("Value of the instance variable age: "+age);
   }
}

輸出

Enter the value of name:
Krishna
Enter the value of age:
29
This is the constructor of the demo class
Value of the instance variable name: Krishna
Value of the instance variable age: 29

更新日期:2019-07-30

4K+ 瀏覽量

開啟你的 職業生涯

完成課程即可獲得認證

開始
廣告