• Java super关键字使用及内存图


    示例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.”不能省略;

  • 相关阅读:
    每日站立会议08
    MAVEN常用命令
    android开发环境搭建
    阻止默认事件和阻止事件冒泡
    C#ActiveX安装项目
    System&Software
    poj 1386 Play on Words 有向欧拉回路
    poj 1033
    120.Triangle
    pandas中 transform 函数和 apply 函数的区别
  • 原文地址:https://www.cnblogs.com/homle/p/14232803.html
Copyright © 2020-2023  润新知