一、super调用超类构造函数
super(parameter-list);
parameter-list指定超类中构造函数所需的任何形参,super()必须是在子类构造函数中执行的第一个语句。超类定义的任何形式的构造函数都可以被super()调用,被执行的构造函数就是与实参相匹配的那一个。
当存在多重继承时,super总是引用最靠近的超类的构造函数。例如:C类继承B类,B类继承A类,则C类的构造函数中使用super,引用B类的构造函数。
如果不使用super(),那么就会执行每个超类的默认(无形参)构造函数。
例如:
<span style="font-size:14px;">public class test {
public static void main(String [] args){
new Teacher("one", 62);
new Teacher("two", 180);
new Teacher("three", 65, 188);
}
}
class Human {
static private float weight;
static private int height;
Human(float weight){
Human.weight = weight;
System.out.println(Human.weight);
}
Human(int height){
Human.height = height;
System.out.println(Human.height);
}
Human(float weight, int height){
Human.weight = weight;
Human.height = height;
System.out.println(Human.weight + " " + Human.height);
}
}
class Teacher extends Human {
static private String s;
Teacher(String s, float weight){
super(weight);
Teacher.s = s;
System.out.println(Teacher.s);
}
Teacher(String s, int height){
super(height);
Teacher.s = s;
System.out.println(Teacher.s);
}
Teacher(String s, float weight, int height){
super(weight, height);
Teacher.s = s;
System.out.println(Teacher.s);
}
}
</span>
结果:
62
one
180
two
65.0 188
three
二、super访问超类的成员
例如:
<span style="font-size:14px;">public class test {
public static void main(String [] args){
new Teacher("three", 65, 188);
}
}
class Human {
static public float weight;
static public int height;
}
class Teacher extends Human {
static private String s;
Teacher(String s, float weight, int height){
super.weight = weight;
super.height = height;
Teacher.s = s;
System.out.println(super.weight);
System.out.println(super.height);
System.out.println(Teacher.s);
}
}</span>
结果:
65.0
188
three