在Java中,構(gòu)造函數(shù)是一種特殊的方法,用于初始化對(duì)象的狀態(tài)。構(gòu)造函數(shù)的名稱與類名相同,沒(méi)有返回類型。當(dāng)創(chuàng)建類的對(duì)象時(shí),構(gòu)造函數(shù)會(huì)被自動(dòng)調(diào)用。以下是使用構(gòu)造函數(shù)初始化對(duì)象的幾種方法:
public class Person {
private String name;
private int age;
// 默認(rèn)構(gòu)造函數(shù)
public Person() {
this.name = "";
this.age = 0;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person(); // 調(diào)用默認(rèn)構(gòu)造函數(shù)
}
}
public class Person {
private String name;
private int age;
// 參數(shù)化構(gòu)造函數(shù)
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
}
}
this()
關(guān)鍵字。public class Person {
private String name;
private int age;
// 默認(rèn)構(gòu)造函數(shù)
public Person() {
this("", 0); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
}
// 參數(shù)化構(gòu)造函數(shù)
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
Person person1 = new Person(); // 調(diào)用默認(rèn)構(gòu)造函數(shù)
Person person2 = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
}
}
final
關(guān)鍵字:如果類的實(shí)例一旦創(chuàng)建就不能被修改,可以使用final
關(guān)鍵字修飾構(gòu)造函數(shù)。public final class Person {
private final String name;
private final int age;
// 參數(shù)化構(gòu)造函數(shù)
public Person(String name, int age) {
this.name = name;
this.age = age;
}
}
public class Main {
public static void main(String[] args) {
try {
Person person = new Person("John", 30); // 調(diào)用參數(shù)化構(gòu)造函數(shù)
} catch (Exception e) {
e.printStackTrace();
}
}
}