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