Java中的“ this”参考

这个关键字

'this'关键字用于引用当前正在使用的对象。以下是使用此关键字的方案。

  • 它用于区分传递的参数与实例变量。

  • 它用于调用当前的类构造函数。

  • 它用于返回当前对象。

  • 它用于将当前对象作为方法参数传递。

  • 它用于调用当前对象的方法。

  • 它用于将当前对象作为构造函数参数传递。

示例

创建一个名为Tester的Java类。

测试器

public class Tester {
   private int a, b;

   //方案1:
   //用于区分通过实例变量传递的参数。
   public Tester(int a, int b) {
      this.a = a;// a = a has no effect, so 'this' is required.
      this.b = b;
   }

   //方案2:
   //用于调用当前类的构造函数
   public Tester() {
      this(0,0);//Tester(0,0) : throws error: Method Tester is undefined.
   }

   //方案3:
   //可以用来返回当前对象
   public Tester getCurrentObject() {
      return this;
   }

   //方案4:
   //可以用来传递当前对象
   private void display(Tester tester) {
      tester.display();
   }

   public void displayValues() {
      display(this);
   }

   //方案5:
   //可以用来调用当前对象的方法
   public void print() {
      this.display();
   }
    //方案6:
   //可用于将当前对象作为构造函数参数传递。
   public Tester(Tester tester) {
      this.a = tester.a;
      this.b = tester.b;
   }

   public void display() {
      System.out.println("a = " + a + ", b = " + b);
   }

   public static void main(String args[]) {
      Tester tester = new Tester(1,2);
      System.out.println("方案1: ");
      tester.display();

      Tester tester1 = new Tester();
      System.out.println("方案2: ");
      tester1.display();

      System.out.println("方案3: ");
      tester.getCurrentObject().display();

      System.out.println("方案4: ");
      tester.displayValues();

      System.out.println("方案5: ");
      tester.print();

      Tester tester2 = new Tester(tester);
      System.out.println("方案6: ");
      tester2.display();    
   }
}

输出结果

编译并运行文件以验证结果。

方案1:  
a = 1, b = 2
方案2:  
a = 0, b = 0
方案3:  
a = 1, b = 2
方案4:  
a = 1, b = 2
方案5:  
a = 1, b = 2
方案6:  
a = 1, b = 2