"这个"java的询问点

1 java this

这里的休闲Android开发人员,我猜的是一个简单的查询.

我想知道"这个"在java/Android中究竟是什么意思.偶尔你会把它看作某些方法的固有部分,但我很好奇它究竟是指什么.谢谢!

Grz*_*ski 5

从我的观点来看,这是:

  • 五十个Java关键字之一
  • 对当前对象的特殊(例如只读)引用

您可以在四种不同的上下文中使用它:

  1. 指向当前对象的字段和方法(this.)
  2. 指向当前对象本身(例如Object object = this;)
  3. 在另一个构造函数中调用构造函数(this())
  4. (限定于此)指向(非静态)内部类中的外部对象(例如,OuterClassName.this.OuterClassField)

为了更好地理解你需要一些例子:

class Box {
   // Implementing Box(double width = 1, double length = 1, double height = 1):
   Box(double width, double length, double height) {         
      this.width = width; // width is local parameter
      this.length = length; // this.length is object's field
      this.height = height;
   }
   Box(double width, double length) {
      // no statements here allowed
      this(width, length, 1);
      // you can call at most one constructor (recursion not allowed)
   }
   Box(double width) {
      this(width, 1, 1);
   }
   Box() {
      this(1, 1, 1);
      System.out.println("I am default constructor");
   }
   public double getWidth() {
       return this.width; // explicit way (width means the same)
       // return Box.this.width; // full-explicit way
   }
   public void showWidth() {
       System.out.println(this.getWidth());
   }
   public void showWidthAlternate() {
       Box box = this; // the same as explicitly Box box = Box.this;
       // this = box; // can't touch me (read-only reference)
       System.out.println(box.width);
   }
   private double width, length, height;
}
Run Code Online (Sandbox Code Playgroud)

更多信息: