浅谈Java中的this用法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_40718168/article/details/83345966

基本用法

1.  this.变量名代表当前对象的成员变量。this.方法名代表当前对象的成员方法。this代表当前对象。

2. 当在内部类或匿名类中时,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();
    }
}

上述代码转自 https://www.cnblogs.com/nolonely/p/5916602.html

上述代码表明在匿名类中如想使用外部类的方法,就在this前面加外部类名就可以引用外部类的方法,this此时代表当前匿名类thread。

3.  在构造函数中,通过this可以调用同一类中别的构造函数,当要注意一下几点:

     a. 在构造函数中调用时,this必须写在首行位置

     b. 在一个构造函数中只能使用this调用一次别的构造函数

     c .在非构造函数中不能使用this调用构造函数

猜你喜欢

转载自blog.csdn.net/qq_40718168/article/details/83345966