刘文涛

Flex3,Struts2,Hibernate3,Spring2,UML,Oracle,mysql,tomcat,compass,lucene

   :: 首页 ::  ::  ::  :: 管理 ::

2006年8月26日 #

1. this是指当前对象自己。

当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中:

 1public class A {
 2    String s = "Hello";
 3    public A(String s) {
 4        System.out.println("s = " + s);
 5        System.out.println("1 -> this.s = " + this.s);
 6        this.s = s;
 7        System.out.println("2 -> this.s = " + this.s);
 8    }

 9
10    public static void main(String[] args) {
11        new A("HelloWorld!");
12    }

13}


运行结果:

1= HelloWorld!
21 -> this.s = Hello
32 -> this.s = HelloWorld!


在这个例子中,构造函数A中,参数s类A的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类A的变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对参数s进行打印结果;后面两行分别是对对象A的变量s进行操作前后的打印结果。

2. 把this作为参数传递

当你要把自己作为参数传递给别的对象时,也可以用this。如:

1public class A {
2    public A() {
3        new B(this).print();
4    }

5
6    public void print() {
7        System.out.println("Hello from A!");
8    }

9}


 1public class B {
 2    A a;
 3
 4    public B(A a) {
 5        this.a = a;
 6    }

 7
 8    public void print() {
 9        a.print();
10        System.out.println("Hello from B!");
11    }

12}

13

运行结果:

1Hello from A!
2Hello from B!


在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。

3. 注意匿名类和内部类中的中的this。

有时候,我们会用到一些内部类和匿名类。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如下面这个例子:

 1public class A {
 2    int i = 1;
 3
 4    public A() {
 5        Thread thread = new Thread() {
 6            public void run() {
 7                for(;;) {
 8                    A.this.run();
 9                    try {
10                        sleep(1000);
11                    }
 catch(InterruptedException ie) {
12                    }

13                }

14            }

15        }
;
16        thread.start();
17    }
 
18
19    public void run() {
20        System.out.println("i = " + i);
21        i++;
22    }

23
24    public static void main(String[] args) throws Exception {
25        new A();
26    }

27
28}

在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run
posted @ 2006-08-26 20:24 刘文涛| 编辑 收藏