this关键字

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 constructor x is a local copy of the contructor's first argument. To refer to the Point field x, the constructor must use this.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:在一个构造器中调用另一个构造器的行为必须写在第一行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值