Java编程中的构造函数链接
构造函数链接是指从其他构造函数调用一个构造函数。它有两种类型。
在相同的类中-使用this()关键字引用当前类的构造函数。确保这this()是构造函数的第一个语句,并且至少应有一个不使用该this()语句的构造函数。
从超级/基类-使用super()关键字引用父类构造函数。确保这super()是构造函数的第一条语句。
示例
class A {
public int a;
public A() {
this(-1);
}
public A(int a) {
this.a = a;
}
public String toString() {
return "[ a= " + this.a + "]";
}
}
class B extends A {
public int b;
public B() {
this(-1,-1);
}
public B(int a, int b) {
super(a);
this.b = b;
}
public String toString() {
return "[ a= " + this.a + ", b = " + b + "]";
}
}
public class Tester {
public static void main(String args[]) {
A a = new A(10);
System.out.println(a);
B b = new B(11,12);
System.out.println(b);
A a1 = new A();
System.out.println(a1);
B b1 = new B();
System.out.println(b1);
}
}输出结果
[ a= 10] [ a= 11, b = 12] [ a= -1] [ a= -1, b = -1]
热门推荐
10 祝女儿简短祝福语大全
11 大学新年祝福语简短创意
12 元旦适合的祝福语简短
13 朋友出远门祝福语简短
14 初六简短的祝福语
15 祝男孩生日祝福语简短
16 同事调离的祝福语简短
17 拜年红包的祝福语简短
18 妈妈生日祝福语简短励志