Chinaunix首页 | 论坛 | 博客
  • 博客访问: 1449668
  • 博文数量: 3500
  • 博客积分: 6000
  • 博客等级: 准将
  • 技术积分: 43870
  • 用 户 组: 普通用户
  • 注册时间: 2008-05-03 20:31
文章分类

全部博文(3500)

文章存档

2008年(3500)

我的朋友

分类:

2008-05-04 19:07:49

一起学习
谈谈 Java 中 this 的使用 1. this是指当前对象自己。 当在一个类中要明确指出使用对象自己的的变量或函数时就应该加上this引用。如下面这个例子中: public class A { String s = "Hello"; public A(String s) { System.out.println("s = " s); System.out.println("1 -> this.s = " this.s); this.s = s; System.out.println("2 -> this.s = " this.s); } public static void main(String[] args) { new A("HelloWorld!"); } } 运行结果: s = HelloWorld! 1 -> this.s = Hello 2 -> this.s = HelloWorld! 在这个例子中,构造函数A中,参数s与类A的变量s同名,这时如果直接对s进行操作则是对参数s进行操作。若要对类A的变量s进行操作就应该用this进行引用。运行结果的第一行就是直接对参数s进行打印结果;后面两行分别是对对象A的变量s进行操作前后的打印结果。 2. 把this作为参数传递 当你要把自己作为参数传递给别的对象时,也可以用this。如: public class A { public A() { new B(this).print(); } public void print() { System.out.println("Hello from A!"); } } public class B { A a; public B(A a) { this.a = a; } public void print() { a.print(); System.out.println("Hello from B!"); } } 运行结果: Hello from A! Hello from B! 在这个例子中,对象A的构造函数中,用new B(this)把对象A自己作为参数传递给了对象B的构造函数。 3. 注意匿名类和内部类中的中的this。 有时候,我们会用到一些内部类和匿名类。当在匿名类中用this时,这个this则指的是匿名类或内部类本身。这时如果我们要使用外部类的方法和变量的话,则应该加上外部类的类名。如下面这个例子: public class A { int i = 1; public A() { Thread thread = new Thread() { public void run() { for(;;) { A.this.run(); try { sleep(1000); } catch(InterruptedException ie) { } } } }; thread.start(); } public void run() { System.out.println("i = " i); i ; } public static void main(String[] args) throws Exception { new A(); } } 在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run。 下载本文示例代码


浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用浅谈 Java 中 this 的使用
阅读(194) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~