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() 用于父类初始化
来源:程序园用户自行投稿发布,如果侵权,请联系站长删除
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作! |