super关键字
super的基本语法
- super.
xxxxx
作为基本格式 - super可以访问父类中非私有的属性和方法。
- super访问父类的构造器,只能在子类构造器的第一句出现,而且只出现一次。
super使用细节
在子类通过super访问父类的方法/成员
-
通过super访问一个子类和父类同名的方法/成员,会跳过当前类,直接去父类去找,如果不加super,就会现在这个类找,找不到再去父类。
-
通过子类去调用构造器,加了super也是直接去父类中找。
-
this.
成员
/变量
= 不加this或super直接调用成员/变量
案例的code如下,我们在父类,子类中都创建有相同名字的方法
和成员
测试结果与上述结论一致:
father.java
public class father {father() {}father(String name, int age) {}father(String name) {}public void Cal() {System.out.println("这是father类中的Cal调用");}public String getName() {return this.m_Name;}protected int getTresure() {return this.m_Tresure;}private String[] getWife() {return this.m_Wifes;}public String m_Name = "老王";public String m_Flag = "father";protected int m_Tresure = 1_000_000;private String[] m_Wifes = {"丽丽", "大雷"};}
Son.java
public class Son extends father{public void hi() {System.out.println(super.m_Name);System.out.println(super.m_Tresure);System.out.println(super.getTresure());System.out.println(super.getName());}public Son() {super("sdf", 100);}public void Cal() {System.out.println("这是Son类中的Cal调用");}public void test01() {Cal();this.Cal();super.Cal();}public void test02() {System.out.println(m_Flag);System.out.println(this.m_Flag);System.out.println(super.m_Flag);}public String m_Flag = "Son";}
super01
作为主函数调用
public class Super01 {public static void main(String[] args) {Son s1 = new Son();s1.test02();}
}