this 关键字

来源:互联网 发布:运维工程师要编程吗 编辑:程序博客网 时间:2024/05/13 21:03
如果有同一类型的两个对象,分别是 a 和 b。你可能想知道,如何才能分别为这两个对象调
用 f( )呢:


class Banana { void f(int i) { /* ... */ } }
Banana a = new Banana(), b = new Banana(); 
a.f(1);
b.f(2);


如果只有一个 f( )方法,它是如何知道被 a 还是被 b 所调用的呢?


为了能用简便、面向对象的语法来编写代码——即“发送消息给对象”,编译器做了一些幕
后工作。它暗自把“所操作对象的引用”作为第一个参数传递给 f( )。所以上述两个方法的
调用就变成了这样:


Banana.f(a,1);
Banana.f(b,2);
 






这是内部的表示形式。你并不能这样书写代码,并试图通过编译。但这种写法的确能帮你对
实际发生的事情有所了解。


假设你希望在方法的内部获得对当前对象的引用。由于这个引用是由编译器“偷偷”传入的,
所以没有标识符可用。因此,有个可供你使用的专门的关键字:this。this 关键字只能在方
法内部使用,表示对“调用方法的那个对象”的引用。this 的用法和其它对象引用并无不同。
但要注意,如果在方法内部调用同一个类的方法,就不必使用 this,直接调用即可。当前方
法中的 this 引用会自动应用于同一类中的其他方法。所以你能写这样的代码:


class Apricot { 
void pick() { /* ... */ } 
void pit() { pick(); /* ... */ } 
}


在pit( )内部,你可以写this.pick( ),但无此必要2。编译器能帮你自动添加。只有当你需要明
确指出当前对象的引用时,才需要使用this关键字。例如,当需要返回对当前对象的引用时,
就常常在return语句里这么写:


//: c04:Leaf.java
// Simple use of the "this" keyword.
import com.bruceeckel.simpletest.*; 


public class Leaf { 
static Test monitor = new Test(); 
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(); 
    monitor.expect(new String[] { 
"i = 3"
    });
  }
} ///:~
由于 increment( )通过 this 关键字返回了对当前对象的引用,所以很容易在一条语句里对同

一个对象执行多次操作。


原创粉丝点击