Fork me on GitHub

super关键字

使用super调用父类的构造方法
子类不继承父类的构造方法,因此,子类如果想使用父类的构造方法,必须在子类的构造方法中使用,必须使用关键字super来表示,而且super必须是子类构造方法中的头一条语句
Student5_6.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Student5_6 {
int number;
String name;
Student5_6(){
}
Student5_6(int number, String name){
this.number= number;
this.name= name;
}
public int getNumber(){
return number;
}
public String getName() {
return name;
}
}

UniverStudent.java

1
2
3
4
5
6
7
8
9
public class UniverStudent extends Student5_6 {
boolean isNarriage;//子类新增的结婚属性
UniverStudent(int number, String name, boolean v){
super(number, name);//调用父类的构造方法
}
public boolean getIsNarriage(){
return isNarriage;
}
}

Example5_6.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
public class Example5_6 {
public static void main(String[] args) {
UniverStudent zhangStudent= new UniverStudent(20111, "张三", false);
int number= zhangStudent.getNumber();
String name= zhangStudent.getName();
boolean marriage= zhangStudent.getIsNarriage();
System.out.println(name+ "的学号是: "+ number);
if(marriage== true){
System.out.println(name+ "已婚");
}
else {
System.out.println(name+ "未婚");
}
}
}

使用super操作被隐藏的成员变量和方法
如果在子类中想使用被子类隐藏的成员变量或方法,可以使用关键字super,super.x、super.play(),就是访问和调用被子类隐藏的成员变量x和方法play()
Sum.java

1
2
3
4
5
6
7
8
9
10
public class Sum {
int n;
public double f(){
double sum= 0;
for(int i= 1; i<= n;i++){
sum= sum+ i;
}
return sum;
}
}

Average.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class Average extends Sum {
double nm;
public double fq(){
double c;
super.n= (int)nm;
c= super.f();
return c+ nm;
}
public double g(){
double c;
c= super.f();
return c- nm;
}
}

Example5_7.java

1
2
3
4
5
6
7
8
9
10
public class Example5_7 {
public static void main(String[] args) {
Average average= new Average();
average.nm= 100.5678;
double result1= average.fq();
double result2= average.g();
System.out.println("result1= "+ result1);
System.out.println("result2= "+ result2);
}
}

Your support will encourage me to continue to create!