如何使用 Java 建立預設建構函式?
預設建構函式(無引數建構函式)
無引數建構函式不接受任何引數,它用其各自的預設值(即物件為 null,浮點數和雙精度數為 0.0,布林值為 false,位元組、短整型、整型和長整型為 0)為類變數例項化。
無需顯式呼叫建構函式,它們在例項化時自動呼叫。
需要記住的規則
定義建構函式時,應記住以下幾點。
建構函式沒有返回型別。
建構函式的名稱與類名稱相同。
建構函式不能為抽象、final、static 和 Synchronized。
可對建構函式使用訪問修飾符 public、protected 和 private。
示例
class NumberValue {
private int num;
public void display() {
System.out.println("The number is: " + num);
}
}
public class Demo {
public static void main(String[] args) {
NumberValue obj = new NumberValue();
obj.display();
}
}輸出
The number is: 0
示例
public class Student {
public final String name;
public final int age;
public Student(){
this.name = "Raju";
this.age = 20;
}
public void display(){
System.out.println("Name of the Student: "+this.name );
System.out.println("Age of the Student: "+this.age );
}
public static void main(String args[]) {
new Student().display();
}
}輸出
Name of the Student: Raju Age of the Student: 20
廣告
資料結構
網路
關係資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP