博客
关于我
java —— this 关键字
阅读量:289 次
发布时间:2019-03-03

本文共 793 字,大约阅读时间需要 2 分钟。

什么时候用this?

在编写Java程序时,遇到可能产生二义性的情况,可以通过使用this关键字来明确指向当前对象;

普通方法中的this

在普通方法中,this关键字用于指代调用该方法的对象。例如:

public void getSum() { System.out.println(this.t1 + this.t2);}

构造方法中的this

在构造方法中,this关键字用于指代要初始化的对象。例如:

public Score(int t1) { this.t1 = t1;}

此外,构造方法中通常还会初始化其他变量:

public Score(int t1, int t2) { this.t1 = t1; this.t2 = t2;}

注意事项

需要注意以下几点:

1. this关键字不能用于static方法。因为static方法属于类,而不是对象,无法使用this关键字。

2. 在构造方法中,this关键字必须是第一行代码,否则会导致编译错误。

代码示例

以下是一个完整的代码示例:

class Score { int t1, t2; public Score(int t1) { this.t1 = t1; } public Score(int t1, int t2) { this.t1 = t1; this.t2 = t2; } public void getSum() { System.out.println(this.t1 + this.t2); }}

并在主类中测试:

public class TestConstructor { public static void main(String[] args) { Score s1 = new Score(10); Score s2 = new Score(5, 15); s2.getSum(); }}

转载地址:http://whsl.baihongyu.com/

你可能感兴趣的文章
Openlayers实战:绘制带箭头的线
查看>>
Openlayers实战:绘制点、线、圆、多边形
查看>>
Openlayers实战:绘制矩形,正方形,正六边形
查看>>
Openlayers实战:自定义放大缩小,显示zoom等级
查看>>
Openlayers实战:自定义版权属性信息
查看>>
Openlayers实战:输入WKT数据,输出GML、Polyline、GeoJSON格式数据
查看>>
Openlayers实战:选择feature,列表滑动,定位到相应的列表位置
查看>>
Openlayers实战:非4326,3857的投影
查看>>
Openlayers高级交互(1/20): 控制功能综合展示(版权、坐标显示、放缩、比例尺、测量等)
查看>>
Openlayers高级交互(10/20):绘制矩形,截取对应部分的地图并保存
查看>>
Openlayers高级交互(11/20):显示带箭头的线段轨迹,箭头居中
查看>>
Openlayers高级交互(12/20):利用高德逆地理编码,点击位置,显示坐标和地址
查看>>
Openlayers高级交互(13/20):选择左右两部分的地图内容,横向卷帘
查看>>
Openlayers高级交互(14/20):汽车移动轨迹动画(开始、暂停、结束)
查看>>
Openlayers高级交互(15/20):显示海量多边形,10ms加载完成
查看>>
Openlayers高级交互(16/20):两个多边形的交集、差集、并集处理
查看>>
Openlayers高级交互(17/20):通过坐标显示多边形,计算出最大幅宽
查看>>
Openlayers高级交互(18/20):根据feature,将图形适配到最可视化窗口
查看>>
Openlayers高级交互(19/20): 地图上点击某处,列表中显示对应位置
查看>>
Openlayers高级交互(2/20):清除所有图层的有效方法
查看>>