来自 the java tutorial我看到一个类可以有两个不同的构造函数,区别在于每个构造函数中提供的参数数量,它们还给出了无构造函数参数的示例。基于这些信息和他们的例子。我已经写了这门课以获得更好的理解。我还注意到可以使用 getter 和 setter 方法更改无参数构造函数中的字段,因此我看不出与具有参数的构造函数有什么区别。我在这里阅读了一些问题,但他们没有解决这个问题。
我的问题:是否存在应该使用此类构造函数的特定情况?如果是,其背后的原因是什么?有什么好处吗?
public class Course {
int numberOfStudents;
String courseName;
String courseLecturer;
public Course() {
this.courseName = "Human Science";
this.courseLecturer = "Jane Doe";
this.numberOfStudents = 22;
}
public Course(String courseName, String courseLecturer, int numberOfStudents) {
this.courseName = courseName;
this.courseLecturer = courseLecturer;
this.numberOfStudents = numberOfStudents;
}
public String getCourseName() {
return this.courseName;
}
public void setCourseName(String courseName) {
courseName = this.courseName;
}
public static void main(String[] args) {
Course courseType2 = new Course("CIV4046F", "Obi", 45);
System.out.println(courseType2.getCourseName());
}
}
最佳答案
不,用“看起来很逼真”过于专业的魔法值定义默认构造函数不是一个好主意,它只会在以后的调试过程中造成麻烦(“我们的数据库出了什么问题,这个 Jane Doe 是从哪里来的来自?”)。
当存在一些“规范默认值”时,覆盖默认构造函数可能更有意义。例如,如果您正在为分数建模,则将分子设置为 0
并将分母设置为 1
将提供零作为分数的良好默认表示。
关于java - 了解没有参数但有类变量的Java构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50352165/