- 关键字this可以调用本类的构造器或方法,关键字super可以调用父类的构造器或方法。
- 使用this调用本类其他构造器或使用super调用父类构造器时,this或super必须放在构造器中的第一行,而且一个构造器最多存在一个this或super。
- 如果一个类声明了n个构造器,则最多允许n-1个构造器使用this调用本类其他构造器,以免出现环路、陷入死循环。
- 若构造器中没有使用this或super调用其他构造器,则默认使用super调用父类的空参构造器。
public class ThisAndSuper {
public static void main(String[] args) {
new Test2(2).print();
}
}
class Test1 {
protected int value1;
public Test1() {
this.value1 = 0;
}
public int getValue1() {
return value1;
}
}
class Test2 extends Test1 {
private int value1;
private int value2;
public Test2() {
super();
this.value1 = 1;
}
public Test2(int value2) {
this();
this.value2 = value2;
}
@Override
public int getValue1() {
return value1;
}
public int getValue2() {
return value2;
}
public void print() {
System.out.println("Test1.value1 = " + super.getValue1());
System.out.println("Test2.value1 = " + this.getValue1() + "\tTest2.value2 = " + this.getValue2());
}
}