Java构造函数中使用this()的作用

在阅读nutch源码的时候发现经常会在使用this调用。this调用的作用是调用类本身的已经存在的其它的构造函数。它与super不同,super调用的父类的构造函数。 看如下ntuch中CrawlDatum所有构造函数源码: public CrawlDatum() { } public CrawlDatum(int status, int fetchInterval) { this(); /*this调用的作用是调用上面的无参构造函数*/ this.status = (byte)status; this.fetchInterval = fetchInterval; } public CrawlDatum(int status, int fetchInterval, float score) { this(status, fetchInterval); /*this的作用是调用上面有两个参数的构造函数*/ this.score = score; } 使用this的好处: 1, 实现代码复用。例如上面第三个构造函数如果不使用this就会是这样 public CrawlDatum(int status, int fetchInterval, float score) { this.status = (byte)status; this.fetchInterval = fetchInterval; this.score = score; } 这样的话,前两行代码就完全是第二个构造函数中的语句,违背面向对象代码复用的原则。 2, 封装 如果说第二个构造函数的实现发生了变化,则我们除了修改第二个构造函数,还得修改第三个构造函数。 如果使用this就不需要修改第三个构造函数了。

转载于:https://www.cnblogs.com/afreethinker/p/3270701.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值