zoukankan      html  css  js  c++  java
  • 为什么要有get方法?-多态内存分析的应用

    在处理java类中的成员变量时,并不是采用运行时绑定,而是一般意义上的静态绑定。所以在向上转型的情况下,对象的方法可以找到子类,而对象的属性还是父类的属性。
    代码如下:
    Java代码
    public class Father {

      protected String name="父亲属性";
      
      public void method() {
        System.out.println("父类方法,对象类型:" + this.getClass());
      }
    }
      
    public class Son extends Father {
      protected String name="儿子属性";
      
      public void method() {
        System.out.println("子类方法,对象类型:" + this.getClass());
      }
      
      public static void main(String[] args) {
        Father sample = new Son();//向上转型
        System.out.println("调用的成员:"+sample.name);
      }
    }
    结论,调用的成员为父亲的属性。
    现在试图调用子类的成员变量name,该怎么做?最简单的办法是将该成员变量封装成方法getter形式。
    代码如下:
    Java代码
    public class Father {
      protected String name = "父亲属性";
      public String getName() {
        return name;
      }
      public void method() {
        System.out.println("父类方法,对象类型:" + this.getClass());
      }
    }
      
    public class Son extends Father {
      protected String name="儿子属性";
      
      public String getName() {
        return name;
      }
      
      public void method() {
        System.out.println("子类方法,对象类型:" + this.getClass());
      }
      
      public static void main(String[] args) {
        Father sample = new Son();//向上转型
        System.out.println("调用的成员:"+sample.getName());
      }
    }

    结果:调用的是儿子的属性
    sample是Father类型的,sample可以看到Father类的属性名name,方法名getName和方法名method,当调用getName方法时sample先找到自己的方法名getName,然后拿着方法名getName到代码区找方法体,发现有两个getName方法,虚拟机一看具体的对象是Son,就选择了Son的getName方法

  • 相关阅读:
    CSS 选择器及各样式引用方式
    The usage of docker image wurstmeister/kafka
    kafka connect rest api
    Kafka connect in practice(3): distributed mode mysql binlog ->kafka->hive
    jail-break-rule
    Ubuntu下把缺省的dash shell修改为bash shell
    mysql 5.7 enable binlog
    Docker CMD in detail
    记一次深度系统安装至windows系统盘提示挂载为只读模式问题
    android 监听声音变化
  • 原文地址:https://www.cnblogs.com/lonely-buffoon/p/5572957.html
Copyright © 2011-2022 走看看