Super的基本用法
super 代表父类的引用,用于访问父类的属性、方法、构造器
-
访问父类的的属性,但不能访问父类的private 属性,
语法: super.属性名;
-
访问父类的的方法 ,不能 访问父类的private 方法,
语法:super.方法名(参数列表) ;
-
访问父类的构造器(注意:只能放在构造器第一句)
语法 super( 参数列表);
class A { private int a1=100; protected int a2=200; public int a3=300; int a4=400; public void shou_a1(){ System.out.println(a1); } } class B extends A{ public void show_A(){ System.out.println(super.a2+" "+super.a3+" "+super.a4); super.shou_a1(); } } public class Text { public static void main(String[] args) { B b =new B(); b.show_A(); } } //输出结果 200 300 400 100
使用细节
-
当子类中有和父类的成员(属性和方法)重名时,为了访问父类的成员,必须调用super()
如果没有,使用super,this,直接访问都是一样的效果
class A { //4 个属性 public int n1 = 100; protected int n2 = 200; int n3 = 300; private int n4 = 400; public void cal() { System.out.println("A 类的 cal() 方法..."); } } class B extends A { public int n1=200; public int b1=20; public void sum() { System.out.println("B 类的 sum()"); System.out.println(n3); System.out.println(this.n3); System.out.println(super.n1); //希望调用父类的n1() super.cal(); //希望调用父类的cal() } public void cal() { System.out.println("B 类的 cal() 方法..."); } } public class Test{ public static void main(String[] args) { B b = new B(); b.sum(); //运行结果 B 类的 sum() 300 300 100 A 类的 cal() 方法... //n1 和 this.n2 是等价的 //n1 和 this.n1 查找的规则是 //找 cal 方法时(cal() 和 this.cal()),顺序是: //(1) 先找本类,如果有,则调用 //(2) 如果没有,则找父类(如果有,并可以调用,则调用) //(3) 如果父类没有,则继续找父类的父类,整个规则,就是一样的,直到 Object 类 // 提示:如果查找属性的过程中,找到了,但是不能访问(private), 则报错, cannot access // 如果查找属性的过程中,没有找到,则提示属性不存在 //super.cal()是直接跳到父类中找,整个规则,就是一样的,直到 Object 类 } }
-
super的访问不局限于直接父类,如果爷爷类中有本类同名的成员,也可以使用super去访问爷爷类的成员;
如果有多个父类(上级类)中都有同名的成员,使用super访问接近原则,A->B->C,当然也需要遵循权限的相关规则
-
this 和super区别