java关键字super
super用来引用直接父类对象,每当创建子类的实例时,父类的实例被隐式创建,由super关键字引用变量引用
1,用法
①引用直接父类的实例变量,调用直接父类方法
class Animals{
String color = "red";
void output(){
System.out.println("this is father......");
}
}
class Dog extends Animals{
String color = "green";
void output(){
System.out.println("this is son.......");
super.output();//调用父类方法
System.out.println(color);
System.out.println(super.color);//引用父类变量
}
}
public class ex {
public static void main(String[] args) {
Dog dog = new Dog();
dog.output();
}
}
运行结果
this is son.......
this is father......
green
red
我觉得super调用直接父类的方法有种撤销子类函数覆盖的意思,函数覆盖之后想要是被覆盖了的父类函数显现出来,用到super关键字
②引用直接父类的构造函数
class Animals{
Animals(){
System.out.println("Father's constructor");
}
}
class Dog extends Animals{
Dog(){
super();//若果没有这行代码,编译器也会自动的添加上
System.out.println("Son's constructor");
}
}
public class ex {
public static void main(String[] args) {
Dog dog = new Dog();
}
}
运行结果
Father's constructor
Son's constructor
Process finished with exit code 0
当创建一个子类实例的时候,一定会隐式的创建一个父类实例,既然创建了父类实例,就一定得调用父类的构造函数,所以上例的super();可写可不写,但注意,写了必须放在子类构造函数的第一行。
2,小实例应用
体会一下super的用法
class Student{
String name;
int id;
Student(int id,String name){
this.name = name;
this.id = id;
}
}
class MiddleStudent extends Student{
int grade;
MiddleStudent(int grade,int id,String name) {
super(id,name);//此行代码必须要有
this.grade = grade;
}
}
public class ex {
public static void main(String[] args) {
MiddleStudent s = new MiddleStudent(8,1234,"Mary");
System.out.println(s.grade+" "+s.name+" "+s.id);
}
}
结果
8 Mary 1234
Process finished with exit code 0