第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 声明了三个实例变量:empIdempNameempAge
  • 带参构造函数 Employee 接受三个参数,并使用 this 关键字将它们赋值给实例变量。
  • main 方法中,使用指定的值创建了对象 kumarSystem.out.println(kumar.empId); 会打印 101

带参构造函数允许我们在创建对象时通过参数初始化对象的值。

构造函数中的 this 关键字

什么是 this

this 是指向当前对象的引用变量。

在构造函数中使用 this

当构造函数的参数名与实例变量名相同时,Java 会优先使用参数。此时使用 this 关键字来区分实例变量和参数:

this.empId = empId;
  • this.empId → 当前对象的实例变量
  • empId → 构造函数参数

这确保传入的值被存储到对象中。

Back to Blog

相关文章

阅读更多 »

接口 vs 抽象类

Interface 或 Abstract Class?它们非常相似,因此在何时使用每一种都会让人感到困惑。我将在这篇文章中回答这个问题。