您的位置:首页 > 编程语言 > Java开发

java中的this关键字的总结

2015-11-09 22:52 537 查看
1.在写java bean的seter/geter方法时时经常用到的一种this:当类的成员变量和局部变量的重名的时候this表示方法所在的类,如下:

public class yuege{
private int id;

public void setId(int id){
this.id = id;
}
public int getId(){
return this.id;
}
}


2.
public class yuege2 {
    public yuege2() {
       new yuege1(this).print();// 调用yuege1的方法
    }
}
public class yuege1 {
    public yuege1(yuege2 yuege2) {
       this.yuege2 = yuege2;
    }
    public void print() {
    System.out.println("yuege1!");
    }
}
public class thisTest {
 public static void main(String[] args) {
 yuege2 yuege2 = new yuege2();
}
}
输出:yuege1!

3.

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

public class HelloB {
    int i = 1;
 
    public HelloB() {
       Thread thread = new Thread() {
           public void run() {
              for (int j=0;j<20;j++) {
                  HelloB.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 HelloB();
    }
}


在上面这个例子中, thread 是一个匿名类对象,在它的定义中,它的 run 函数里用到了外部类的 run 函数。这时由于函数同名,直接调用就不行了。这时有两种办法,一种就是把外部的 run 函数换一个名字,但这种办法对于一个开发到中途的应用来说是不可取的。那么就可以用这个例子中的办法用外部类的类名加上 this 引用来说明要调用的是外部类的方法 run。
4.有时候在类中一个构造函数调用另一个构造函数:

public class ThisTest {
    ThisTest(String yuege1) {
       System.out.println(yuege1)
    }
    ThisTest() {
       this("被调用的构造函数!");
    }
 
    public static void main(String[] args) {
       ThisTest test = new ThisTest()
    }
}
构造的test使用的构造函数使用的是无惨的构造方法,无参的构造方法再调用有参并打印。

5.这个就直接抄了。。。。。

this同时传递多个参数。

public class TestClass {
    int x;
    int y;
 
    static void showtest(TestClass tc) {//实例化对象
       System.out.println(tc.x + " " + tc.y);
    }
    void seeit() {
       showtest(this);
    }
 
    public static void main(String[] args) {
       TestClass p = new TestClass();
       p.x = 9;
       p.y = 10;
       p.seeit();
    }
}


输出:9 10
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: