JAVA平台的this关键字

来源:互联网 发布:八爪鱼采集 淘宝 编辑:程序博客网 时间:2024/06/05 17:08

JAVA平台的this关键字,其实和LINUX内核里面的current指针一样.LINUX内核中的current指针永远指向当前被调度的任务,JAVA平台的this关键字永远指向当前被操作的对象.下面分析JAVA平台this关键字的作用.


1.对字段使用this

    当对象的一个被方法或构造器的参数屏蔽时,可以用关键字this来实现对类字段的访问.如下:

public class Point{    public int x = 0;    public int y = 0;      public Point(int x,int y){        this.x = x;        this.y = y;    }}
上述代码中字段里面的"x"、"y"和构造器的参数重叠了.可以用关键字this来表明操作的是类对象的字段而不是构造器的参数.


2.对构造器使用this

    在一个构造器中,还可以使用this关键字来调用同一个类中的另外构造器,如下面:

public class Rectangle{    private int x,y;    private int width,height;    public Rectangle(){        this(0,0,0,0);    }    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;    }    ...}
在这里需要注意的是,比如我们名义上调用的是构造器Rectanle(),由于内部封装了this(0,0,0,0).JAVA平台会根据签名实际调用的是Rectangle(int x,int y,int width,int height)构造器.

原创粉丝点击