Java中this()与super()的区别解析

this() 的用法

  • 功能:调用当前类的其他构造函数
  • 作用:避免构造函数中的代码重复
  • 限制:必须是构造函数的第一条语句
  • 适用场景:当类中存在多个构造函数且需要共享部分初始化逻辑时
class Car {
    private String color;
    private String model;
    
    // 无参构造函数
    public Car() {
        this("Unknown", "Unknown"); // 调用双参构造函数
    }
    
    // 双参构造函数
    public Car(String color, String model) {
        this.color = color;
        this.model = model;
    }
}

super() 的用法

  • 功能:调用父类的构造函数
  • 作用:初始化父类成员变量
  • 限制:必须是子类构造函数的第一条语句;若父类没有无参构造函数,必须显式调用
  • 适用场景:子类需要初始化父类部分时
class Vehicle {
    private String brand;
    
    public Vehicle(String brand) {
        this.brand = brand;
    }
}
 
class Car extends Vehicle {
    private String model;
    
    public Car(String brand, String model) {
        super(brand); // 调用父类构造函数
        this.model = model;
    }
}

关键区别

  • this() 调用当前类的构造函数,super() 调用父类的构造函数
  • 两者都必须是构造函数的第一条语句
  • this() 用于代码复用,super() 用于父类初始化

来源链接:https://www.cnblogs.com/Saintwaters/p/19024722

© 版权声明
THE END
支持一下吧
点赞14 分享
评论 抢沙发
头像
请文明发言!
提交
头像

昵称

取消
昵称表情代码快捷回复

    暂无评论内容