第12天:理解 Java 构造函数
发布: (2026年1月8日 GMT+8 23:35)
3 min read
原文: Dev.to
Source: Dev.to
什么是构造函数?
构造函数是 Java 中的一种特殊方法,在创建对象时会自动调用。
- 构造函数的名称必须与类名相同。
- 它没有返回类型。
- 在创建对象时会自动调用。
- 用于初始化实例变量。
为什么需要构造函数?
构造函数有助于:
- 初始化对象的值。
- 减少额外的 setter 方法。
- 确保对象以有效状态创建。
- 提升代码可读性和结构。
class Student {
Student() {
System.out.println("Constructor called");
}
}
当创建 Student 对象时,构造函数会自动执行。
构造函数的类型
Java 主要有两种构造函数:
默认构造函数
默认构造函数是没有参数的构造函数。
class Employee {
Employee() {
System.out.println("Hi");
}
public static void main(String[] args) {
Employee emp = new Employee();
}
}
当创建对象 emp 时,默认构造函数被调用并打印 Hi。
带参构造函数
带参构造函数接受参数以初始化对象变量。
class Employee {
int empId;
String empName;
int empAge;
Employee(int empId, int empAge, String empName) {
this.empId = empId;
this.empAge = empAge;
this.empName = empName;
}
public static void main(String[] args) {
Employee kumar = new Employee(101, 20, "Kumar");
System.out.println(kumar.empId);
}
}
在此示例中:
- 类
Employee声明了三个实例变量:empId、empName和empAge。 - 带参构造函数
Employee接受三个参数,并使用this关键字将它们赋值给实例变量。 - 在
main方法中,使用指定的值创建了对象kumar。System.out.println(kumar.empId);会打印101。
带参构造函数允许我们在创建对象时通过参数初始化对象的值。
构造函数中的 this 关键字
什么是 this?
this 是指向当前对象的引用变量。
在构造函数中使用 this
当构造函数的参数名与实例变量名相同时,Java 会优先使用参数。此时使用 this 关键字来区分实例变量和参数:
this.empId = empId;
this.empId→ 当前对象的实例变量empId→ 构造函数参数
这确保传入的值被存储到对象中。