天天看点

this关键字理解

1.当类的成员变量和局部变量(类中方法中的变量)重名时,使用this.s代表类中的成员变量。

举例:

public class Hello {
    String s = "Hello";
 
    public Hello(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) {
       Hello x = new Hello("HelloWorld!");
       System.out.println("s=" + x.s);//验证成员变量值的改变
    }
}
           

2.把自己(本类的对象)当作参数传递时,用B(this),也可以用B(this.)(this作当前参数进行传递)

class A {
    public A() {
       new B(this).print();// 调用B的方法
    }
    public void print() {
       System.out.println("HelloAA from A!");
    }
}
class B {
    A a;
    public B(A a) {
       this.a = a;
    }
    public void print() {
       a.print();//调用A的方法
       System.out.println("HelloAB from B!");
    }
}
public class HelloA {
    public static void main(String[] args) {
       A aaa = new A();
       aaa.print();
       B bbb = new B(aaa);
       bbb.print();
    }
}
           

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();
    }
}
           

4.在构造函数中,通过this可以调用在同一类中与本构造函数名字相同但是形参不同的别的构造函数。如:

public class ThisTest {
    ThisTest(String str) {
       System.out.println(str);
    }
    ThisTest() {
       this("this测试成功!");
    }
 
    public static void main(String[] args) {
       ThisTest thistest = new ThisTest();
    }
}
           

值得注意的是:

  1:在构造调用另一个构造函数,调用动作必须置于最起始的位置。

  2:不能在构造函数以外的任何函数内调用构造函数。

  3:在一个构造函数内只能调用一个构造函数。

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();
    }
}