this关键字

来源:互联网 发布:淘宝的专属推荐是什么 编辑:程序博客网 时间:2024/06/12 14:20
this指向要调用的当前对象,并通过该行为来引用对象中的其他部分,也就是另外的函数或构造器。 
Using this with a Field
use "this" when a field is shadowed by a method or constructor parameter.
public class Point{
     public int x = 0;
     pulbic int y = 0;

     //constructor
     public Point(int x, int y){
          this.x = x;
          this.y = y;
     }
}

     Each arugment to the constructor shadows one of the object's fields -- indside the constructorx is a local copy of the contructor's first argument. To refer to the Point field x, the constructor must usethis.x.
当对象属性被构造器或函数的参数覆盖(有重合,比如x=x),需要用this来指向本对象(Point)域。


Using this with a Constructor
在一个类中,利用(本构造器的)this关键字来调用另一个构造器。也就是显式构造器调用(explicit constructor invocation).           
pulbic class Rectangle{
     private int x, y;
     private int width, height;

     public Rectangle(){
          this(0, 0, 1, 1);
     }

     public Rectangle(int width, int height){
          this(0, 0, width, height);
     }
     public Rectangle(int x,int y, int width, int height){
          this.x = x;
          this.y = y;
          this.width = width;
          this.height = height;
     }
     ...
}
构造器名相同,比如有完整的四个默认参数的矩形,以及需要单独传入两个参数的。this都指向对象Rectangle,但却各自目的不同。this(0, 0, 1, 1)可以自己实现矩形。this(0 ,0, width, height)调用了那个具有四个参数的构造器。
编译器根据参数个数与类型来决定调用哪个构造器。这样的行为也就是多态。
PS:在一个构造器中调用另一个构造器的行为必须写在第一行。