Skip to content
第 15 / 250 章后端⏱ 10 分钟阅读

第 15 章:构造器与 this 关键字

学习目标

  • 掌握构造器的定义和重载
  • 理解 this 关键字的用法
  • 学会用构造器链简化代码

一、什么是构造器?

构造器是创建对象时自动调用的特殊方法。

java
public class User {
    private String name;
    private int age;

    // 构造器:方法名 = 类名,无返回类型
    public User(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public static void main(String[] args) {
        User u = new User("张三", 18);  // ① 调用构造器
    }
}

构造器的特征

  1. 方法名 = 类名
  2. 没有返回类型(连 void 都没有)
  3. 不能被 static / final 修饰
  4. 创建对象时自动调用new 触发)

二、默认构造器

如果你没写任何构造器,编译器会自动生成一个无参构造器:

java
public class User {
    private String name;

    // 编译器自动添加:
    // public User() { }
}

// 正常使用
User u = new User();   // ✅ 调用默认构造器

一旦你写了任何构造器,编译器就不再生成:

java
public class User {
    public User(String name) {  // ① 写了有参构造器
        this.name = name;
    }
    // 没有无参构造器了
}

User u = new User();          // ❌ 编译报错:没有无参构造器
User u2 = new User("张三");   // ✅

💡 企业级建议:永远显式写无参构造器,避免隐性坑。

三、构造器重载

java
public class User {
    private String name;
    private int age;
    private String email;

    public User() {
        this("未命名", 0, null);          // ① 调用其他构造器
    }

    public User(String name) {
        this(name, 0, null);              // ② 构造器链
    }

    public User(String name, int age) {
        this(name, age, null);
    }

    public User(String name, int age, String email) {
        this.name = name;
        this.age = age;
        this.email = email;
    }
}

构造器链(this())

java
public User(String name, int age) {
    this(name, age, null);   // ① 必须放在第一行
    // this.name = name;     // ❌ 编译报错:this() 之后不能再写代码
}

四、this 关键字

this 指代当前对象

4.1 区分成员变量和局部变量

java
public class User {
    private String name;

    public void setName(String name) {  // ① 参数 name 遮蔽字段 name
        this.name = name;               // ② this.name 是字段,name 是参数
    }
}

4.2 调用其他构造器

java
public User() {
    this("默认名");       // 调用 User(String name)
}

4.3 返回当前对象

java
public class Builder {
    private String name;
    private int age;

    public Builder setName(String name) {
        this.name = name;
        return this;       // 返回自己,支持链式调用
    }

    public Builder setAge(int age) {
        this.age = age;
        return this;
    }
}

// 链式调用
new Builder().setName("张三").setAge(18);

4.4 作为参数传递

java
public class Printer {
    public void print() {
        System.out.println(this);  // 打印当前对象
    }
}

五、构造器 vs 普通方法

维度构造器普通方法
方法名必须等于类名任意
返回类型没有
调用时机new 时自动手动
存在性必须有(至少默认)可有可无

六、完整代码示例

java
/**
 * 构造器与 this 综合示例
 *
 * 配套文档:第 15 章 构造器与 this 关键字
 */
public class User {
    private String name;
    private int age;
    private String email;

    // ============ 构造器重载 ============
    public User() {
        this("未命名", 0, null);              // 调用三参构造器
        System.out.println("无参构造器");
    }

    public User(String name) {
        this(name, 0, null);
        System.out.println("单参构造器: " + name);
    }

    public User(String name, int age) {
        this(name, age, null);
    }

    public User(String name, int age, String email) {
        this.name = name;                       // ① this 区分成员变量和参数
        this.age = age;
        this.email = email;
    }

    // ============ Getter ============
    public String getName() { return name; }
    public int getAge() { return age; }
    public String getEmail() { return email; }

    // ============ 链式 Setter(返回 this)============
    public User setName(String name) {
        this.name = name;
        return this;
    }

    public User setAge(int age) {
        this.age = age;
        return this;
    }

    public void printInfo() {
        System.out.println("姓名: " + name + ", 年龄: " + age + ", 邮箱: " + email);
    }

    public static void main(String[] args) {
        // 测试构造器重载
        User u1 = new User();
        User u2 = new User("张三");
        User u3 = new User("李四", 25);
        User u4 = new User("王五", 30, "wangwu@example.com");

        u1.printInfo();   // 姓名: 未命名, 年龄: 0, 邮箱: null
        u2.printInfo();   // 姓名: 张三, 年龄: 0, 邮箱: null
        u3.printInfo();   // 姓名: 李四, 年龄: 25, 邮箱: null
        u4.printInfo();   // 姓名: 王五, 年龄: 30, 邮箱: wangwu@example.com

        // 链式调用
        User u5 = new User().setName("赵六").setAge(28);
        u5.printInfo();   // 姓名: 赵六, 年龄: 28, 邮箱: null
    }
}

七、本章小结

要点关键
构造器方法名 = 类名,无返回类型,new 时调用
默认构造器没写任何构造器时编译器自动生成
构造器重载多个构造器参数列表不同
this()调用其他构造器,必须在第一行
this 关键字指代当前对象,区分成员 / 参数

动手练习

练习 1:基础题

Car 类写三个构造器:

java
public Car()                       // 默认:品牌 "Unknown", 速度 0
public Car(String brand)           // 单参
public Car(String brand, int speed) // 双参

this() 实现构造器链。


下一章第 16 章:封装

本站基于 VitePress 构建 · 由 Codebook 团队维护