this关键字
来源:互联网 发布:淘宝的专属推荐是什么 编辑:程序博客网 时间:2024/06/12 14:20
this指向要调用的当前对象,并通过该行为来引用对象中的其他部分,也就是另外的函数或构造器。
Using
this
with a Fielduse "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:在一个构造器中调用另一个构造器的行为必须写在第一行。
阅读全文
0 0
- 关键字this
- this关键字
- this关键字
- this 关键字
- this 关键字
- this关键字
- this关键字
- this 关键字
- this 关键字
- this 关键字
- this关键字
- 关键字this
- 关键字this
- this 关键字
- this 关键字
- this关键字
- this关键字
- This关键字
- swift中单例的使用
- Java Calendar 类的时间操作
- 正则表达式语法
- 查看windows和office激活情况
- Maven下SSM项目整合笔记02:mybatis配置文件以及逆向工程
- this关键字
- modbus RTU 3.5字符时长,1.5字符时长
- 设置zookeeper开机自启动
- php://filter
- Sqlldr装在数据文件脚本
- 2017中国中部(长沙)国际装备制造业博览会会刊(参展商名录)
- Android Studio 快捷键
- Android studio gradle依赖,依赖爆红,fileTree一句代码实现项目lib下的所有jar包全部自动依赖
- (object...params)vararsgs机制详解