5.5 super关键字
5.5.1 super关键字操作被隐藏的成员变量和方法
子类一旦隐藏继承的成员变量或者方法,那么子类创建的对象就不再拥有该方法和变量,该方法和变量将由super关键字负责
子类中使用被子类隐藏继承的成员变量或者方法如下:
//super关键字使用
super.x;
super.play();
//super关键字操作被隐藏的成员变量和方法例子
public class Example5_7_One {
int n;
float f() {
float sum = 0;
for (int i = 1; i < n; i++) {
sum = sum + i;
}
return sum;
}
}
public class Example5_7_Two extends Example5_7_One {
int n;
float f() {
float s;
super.n = n;
s = super.f();
return s - n;
}
float g() {
float s;
s = super.f();
return s - 1;
}
}
public class Example5_7 {
public static void main(String[] args) {
// TODO Auto-generated method stub
Example5_7_Two two = new Example5_7_Two();
two.n = 5;
float two1 = two.f();
float two2 = two.g();
System.out.println(two1);
System.out.println(two2);
}
}
//输出结果为5.0和9.0
5.2.2 使用super调用父类的构造方法
(1)当用子类的构造方法创建一个子类对象时,子类的构造方法总是先调用父类的某个构造方法(子类没有指明调用父类哪个构造方法,就调用无参的构造方法)
(2)构造方法不能继承,所以子类需要在其构造方法中使用super关键字来调用父类构造方法,并且super必须是子类构造方法的第一条语句
super();