我怎样才能简化这个:
是否有必要有两个不同的构造函数,只有一点点不同。
有没有办法只使用其中一个来简化它?
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;
}
}
最佳答案
是的,您可以使用关键字 this
调用另一个构造函数,并且您遵守 DRY 原则(不要重复自己)。
public MyCostructor(int w, int h){
this(w,h,null);
}
您可以阅读更多 here (部分将其与构造函数一起使用)
关于java - 如何简化相似的构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23273083/