-
在构造器中调用this
在构造器中可以使用this(XXX)来调用另一个构造器
public class This {
public static void main(String[] args) {
T t = new T();
}
}
class T {
public int num;
public String name;
public T() {
this(20);
System.out.println("调用了构造器T()");
}
public T(int num) {
this("小明");
this.num = num;
System.out.println("调用了构造器T(int num)");
}
public T(String name) {
this.name = name;
System.out.println("调用了构造器T(String name)");
}
}
运行结果:

注意点:
1. this() 只能在构造器中使用
2. this() 必须写在第一行
634

被折叠的 条评论
为什么被折叠?



