java中的this关键字的总结

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




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值