使用 this() 调用另一个构造函数来避免在重载构造函数中重复相同的代码。
示例代码:
public class Person { private String name; private int age; private String address;
public Person(String name, int age, String address) {
this.name = name;
this.age = age;
this.address = address;
}
public Person(String name, int age) {
this(name, age, "");
}
public Person(String name) {
this(name, 0, "");
}
public Person() {
this("", 0, "");
}
}
上面的 Person 类有四个构造函数,其中每个构造函数都调用不同的 this() 构造函数。这样就避免了在重载构造函数中重复代码的情况。
上一篇:避免在重新渲染后重新获取