示例1:
public class SuperTest{ public static void main(String[] args){ Vip v = new Vip("zhang"); v.shopping(); } } class Customer{ String name; public Customer(){} public Customer(String name){ this.name = name; } } class Vip extends Customer{ public Vip(){ } public Vip(String name){ super(name); } public void shopping(){ //不能使用static,super和this不能用于静态方法中; System.out.println(name + " is shopping..."); //zhang is shopping... System.out.println(this.name + " is shopping..."); //zhang is shopping... System.out.println(super.name + " is shopping..."); //zhang is shopping... } }
创建Vip对象,先调用有参数的Vip构造方法,在有参构造方法中也会先调用父类Customer的有参数构造方法,在有参Customer构造方法中会先调用Object的构造方法;
内存图示意:
所有三个输出结果都是相同的,name前面没有添加引用默认就使用this引用,从内存图中可以看出,super也是this一部分,super中“name=zhang”,所有this也是一样的。
示例2:
super.不能省略的场景:
public class SuperTest01{ public static void main(String[] args){ Vip v = new Vip("zhang"); v.shopping(); } } class Customer{ String name; public Customer(){} public Customer(String name){ this.name = name; } } class Vip extends Customer{ String name; //当子类和父类中有相同的变量名时 public Vip(){ } public Vip(String name){ super(name); //调用父类的有参构造函数,在父类中给 name = zhangsan; //this.name = name; //但是子类中也有一个name属性,这时子类中的name就等于null了; } public void shopping(){ System.out.println(name + " is shopping..."); //null is shopping... System.out.println(this.name + " is shopping..."); //null is shopping... System.out.println(super.name + " is shopping..."); //zhang is shopping... } }
结论:
当子类和父类有相同的属性和方法时,想要在子类中访问父类的属性和方法时,“super.”不能省略;