java如何简化类似的构造函数?
我如何简化这一点:
是否有必要使用两个不同的构造函数,只需一点差异
有没有一种方法可以简单地使用其中的一种
public class MyCostructor {
public MyCostructor(int w, int h, String name) {
this.w = w;
this.h = h;
this.name = name;
}
public MyCostructor(int w, int h) {
this.w = w;
this.h = h;
}
}
# 1 楼答案
在构造函数中使用
this()
:# 2 楼答案
是的,您可以使用关键字
this
来调用另一个构造函数,并且您尊重DRY原则(不要重复)你可以阅读更多的here(使用这个构造函数的部分)