当一个类有多个构造函数时,为了减少代码量,我希望在一个构造函数中调用其他构造函数,此时可以使用使用this指针达到目的。
public class test {
public static void main(String
[] args
) {
Person person1
= new Person();
Person person2
= new Person("张三");
Person person3
= new Person("李四", 18);
}
}
class Person {
String name
;
int age
;
Person() {
System
.out
.println("调用了默认构造函数");
}
Person(String na
) {
name
= na
;
System
.out
.println(name
+ "调用了1个参数的构造函数");
}
Person(String na
, int ag
) {
this(na
);
age
= ag
;
System
.out
.println(name
+ "调用了2个参数的构造函数");
}
}
运行结果:
转载请注明原文地址: https://mac.8miu.com/read-63593.html