super
1 super是什么
严格来说,super 其实并不是一个引用,它只是一个关键字,super 代表了当前对象中从父类继承过来的那部分特征。例如父亲又眼睛鼻子,儿子继承了父亲的眼睛鼻子,但是儿子的眼睛鼻子还是长在儿子身上,如果this指的是儿子,那么super就是儿子身上的眼睛鼻子,super只是对它进行了标记,所以说"this.眼睛"(儿子的眼睛)等同于"super.眼睛"(儿子的眼睛)。
super和this都可以使用在实例方法中。不能共存。
super不能使用在静态方法当中,因为super代表了当前对象上的父类型特征,静态方法中没有this,肯定也是不能使用super的。
super的语法是:“super."、“super()”。
super.大部分情况下是可以省略的。
super()只能出现在构造方法第一行,通过当前的构造方法去调用“父类”中的构造方法,目的是:创建子类对象的时候,先初始化父类型特征。
当一个构造方法第一行:既没有this()又没有super()方法的话,默认会有一个super();表示通过当前子类的构造方法调用父类的无参数构造方法。所以必须保证父类的无参数构造方法是存在的。
2 super使用在构造方法中
不使用super关键字:
/**
* @author wcs
* @date 2021/8/8 10:18
*/
public class SuperTest01 {
public static void main(String[] args) {
Student stu = new Student("12345x", "jack", true, "1111");
System.out.println(stu.id);
System.out.println(stu.name);
System.out.println(stu.sex);
System.out.println(stu.stuNo);
}
}
class People {
String id;
String name;
boolean sex;
public People() {
}
//父类构造方法
public People(String id, String name, Boolean sex) {
this.id = id;
this.name = name;
this.sex = sex;
}
}
class Student extends People {
String stuNo;
public Student() {
}
//子类构造方法
public Student(String id, String name, Boolean sex, String stuNo) {
this.id = id;
this.name = name;
this.sex = sex;
this.stuNo = stuNo;
}
}
运行结果:

以上程序发现,父类构造方法中代码与子类构造方法中前三行代码一样。
加上super关键字后:
//加上super关键字后 的子类构造方法
public Student(String id, String name, Boolean sex, String stuNo) {
super(id, name, sex);
this.stuNo = stuNo;
}
运行结果:

super()的作用主要是:第一,调用父类的构造方法,使用这个构造方法来给当前子类对象初始化父类型特征;第二,代码复用。
3 super使用在实例方法中
super不仅可以访问父类属性,还可以访问父类方法:
/**
* @author wcs
* @date 2021/8/8 12:59
*/
public class SuperTest02 {
public static void main(String[] args) {
Cat c = new Cat("加菲猫");
c.test();
}
}
class Animal {
String name;
public Animal() {
super();//默认的,可以省略。指的是Object类
}
public Animal(String name) {
super();
this.name = name;
}
public void move() {
System.out.println("Animal move!");
}
}
class Cat extends Animal {
String name;//与父类同名属性
public Cat() {
super();//默认的,可以省略。指的是Animal类。
}
public Cat(String name) {
super();//默认的,可以省略,默认调用父类的无参构造方法。
this.name = name;
}
public void move() {
System.out.println("Cat move!");
}
public void test() {
move();
this.move();
super.move();
System.out.println(name);
System.out.println(this.name);
System.out.println(super.name);
}
}
运行结果:

以上程序可以看出:
move()和this.move()都指的是当前对象的方法,super.move()访问的是父类的方法。
name和this.name都指的是当前对象的属性,super.name访问的是父类的属性。
当父类与子类有同名的实例变量的时候,如果想在子类中访问父类的实例变量,super不能省略,实例方法也是如此。