super 关键字
基本介绍
super 代表父类的引用,用于访问父类的属性、方法、构造器
使用细节
(1)属性和方法的访问遵循访问权限原则(即不可以访问 private 修饰的属性和方法)
(2)关于构造器:调用父类构造器的好处(分工明确,父类属性由父类初始化,子类的属性由子类初始化)
(3)当子类中有和父类中的成员(属性和方法)重名时,为了访问父类的成员,必须通过 super 访问,如果没有重名,使用 super,this 直接访问是一样的效果
(4)super 的访问不限于直接父类,如果爷爷类和本类中有同名的成员,也可以使用 super 去访问爷爷类的成员,如果多个基类(上级类)中都有同名的成员,使用super 访问遵循就近原则,A -> B -> C,当然也要遵守访问权限的相关规则
this 和 super 的区别
| No. | 区别点 | this | super |
|---|---|---|---|
| 1 | 访问属性 | 访问本类中的属性,如果本类没有此属性则从父类中继续查找 | 从父类开始查找属性 |
| 2 | 调用方法 | 访问本类中的方法,如果本类没有此方法则从父类继续查找. | 从父类开始查找方法 |
| 3 | 调用构造器 | 调用本类构造器,必须放在构造器的首行 | 调用父类构造器,必须放在子类构造器的首行 |
| 4 | 特殊 | 表示当前对象 | 子类中访问父类对象 |
代码示例
java
// 父类
package prac;
public class father {
int age;
String name;
public father() {
}
public father(int age) {
this.age = age;
}
public father(int age, String name) {
this.age = age;
this.name = name;
}
public void show(){
System.out.println("调用了父类的show方法");
}
}
//子类
package prac;
public class son extends father {
public son() {
super();
System.out.println("调用父类的无参构造器~");
}
public son(int age) {
super(age);
this.age = age;
System.out.println("调用父类构造器public father(int age)");
}
public son(int age, String name) {
super(age, name);
this.age = age;
this.name = name;
System.out.println("调用父类构造器public father(int age, String name)");
}
public void show() {
System.out.println("使用super.age调用父类,super.age:" + super.age);
System.out.println("使用super.name调用父类,super.name:" + super.name);
super.show();
}
}
//主方法
package prac;
public class main {
public static void main(String[] args) {
son son = new son();
System.out.println();
son son1 = new son(18);
System.out.println();
son son2 = new son(18,"jackson");
System.out.println();
son2.show();
}
}
//运行结果
调用父类的无参构造器~
调用父类构造器public father(int age)
调用父类构造器public father(int age, String name)
使用super.age调用父类,super.age:18
使用super.name调用父类,super.name:jackson
调用了父类的show方法