Java this关键字

来源:互联网 发布:本周10月重要经济数据 编辑:程序博客网 时间:2024/06/09 22:33

Java class中定义的method(方法)字节码存在方法区中(什么是方法区?请自行搜索Java内存结构),不论有多少基于这个class的对象,这些对象的method都只有一份,就是方法区中的class method字节码,所有这个class的对象调用的method都来自同一片内存。

Class ThisClass {

    void f(int i) { ... }

    public static void main(String args) {

        ThisClass a = new ThisClass();

        ThisClass b = new ThisClass();

        a.f(2);

        b.f(2);

    }

}


上例中a,b所指向的对象调用的f方法实际上是同一片method字节码,那么f method怎么知道是哪个对象调用的自己呢?其实后台调用的时候并非像代码里一样,编译器帮我们完成了一些工作,后台实际调用的时候会把这个对象本身当成f 的第一个参数传进去,像下面这样:

ThisClass.f(a, 2);

ThisClass.f(b, 2);


上面的例子看不出专递对象句柄到method里有什么用,但是如果在f method中需要用到当前调用对象的句柄(比如需要返回当前对象),我们就需要this关键字。this关键字就指向调用这个method的对象。下例来自Thinking in Java 4th Edition

//: Leaf.java // Simple use of the "this" keyword  public class Leaf {   private int i = 0;   Leaf increment() {     i++;     return this;   }   void print() {     System.out.println("i = " + i);   }   public static void main(String[] args) {     Leaf x = new Leaf();     x.increment().increment().increment().print();   } } ///:~ 

this关键字常用于class构造方法中:

class ThisClass {int num = 0;ThisClass(int i) {num = i;}ThisClass() {this(10);}}

对于static方法,编译器并没有在后台‘秘密’转入调用它的对象,因为调用static方法不需要对象,所以static method是没有this变量的。

0 0