zoukankan      html  css  js  c++  java
  • “this” pointer

    As usual, a sample first.
    ==========================
    package ch.allenstudy.newway01;

    public class ThisPointer {

    public static void main(String[] args) {
    A aa1 = new A(10);
    A aa2 = new A(20);
    aa1.show();
    aa2.show();
    }

    }

    class A {
    public int i;

    public A(int a) {
    i = a;
    }

    public void show() {
    System.out.printf(“i = %d\n”, i);
    }
    }
    ==========================================
    In the memory it’s like this:

    So you see, the aa1 and aa2 are in the stack, new A() are in the heap, but all the methods are stored in the code segment part, not in heap or stack.

    If all objects are using the same methods in the memory, aa1′s value is 10, aa2′s value is 20. how do they avoid the conflict for using different parameter values?
    The answer is: they are using a hidden “this” pointer.

    If convert the up code into a C style of code, it maybe like:
    ————————————
    package ch.allenstudy.newway01;

    public class ThisPointer {

    public static void main(String[] args) {
    A aa1 = new A(10);
    A aa2 = new A(20);
    aa1.show();
    aa2.show();
    }

    }

    class A {
    public int i;

    public A(int a) {
    i = a;
    }

    public void show(A * this) {
    System.out.printf(“i = %d\n”, (*this).i);
    }
    }
    =============================
    This 是一个系统隐含的指针被自动附加在非静态的成员函数参数列表中。当前时刻,那个对象调用该函数,那么this就指向当前调用该函数的对象。系统会自动在该 函数的参数列表中添加一个银行的this指针,并把调用该函数的对象地址付给this指针,这样在函数内部通过this就可以访问当前正在调用该函数的对 象的成员。静态(static)函数内部没有this指针。

    Another sample:
    ———————–
    package ch.allenstudy.newway01;

    public class ThisPointer
    {
    private String name; //”name” is a property of the class
    private int age; //”age” is another property of the class

    public ThisPointer(String name, int age)
    {
    this.name = name; //this.name means the property “name”.
    this.age = age; //this.age means the property “age”.
    }

    public void showInformation()
    {
    System.out.printf(“%d\n”,this.name);
    }

    }

  • 相关阅读:
    TMF大数据分析指南 Unleashing Business Value in Big Data(一)
    TMF接口标准MTOSI演进路线图
    移动端开发:使用jQuery Mobile还是Zepto
    拖动插件的一些常见问题
    前端开发资料详解
    AngularJS源码解析3:RootScope的创建过程
    AngularJS源码解析2:注入器的详解
    AngularJS源码解析1:angular自启动过程
    angular核心原理解析3:指令的执行过程
    angular核心原理解析2:注入器的创建和使用
  • 原文地址:https://www.cnblogs.com/backpacker/p/2271546.html
Copyright © 2011-2022 走看看