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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP