background image

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) {