我有一个创建新对象 Student 并将其添加到数组列表 studentRegister 的方法:
public void addStudent(String name, String age)
{
studentRegister.add(new Student(name, age));
}
它在这里调用了 Student 类的构造函数:
public Student(String name, String age)
{
this.name = name;
this.age = age;
}
这可行,但不利于可维护性,因为我必须更改 Student 类和 addStudent 方法中的任何其他参数。如何在 addStudent 阶段输入参数而不在 addStudent 方法中对它们进行硬编码?
最佳答案
只需这样做:
public void addStudent(Student s)
{
studentRegister.add(s);
}
在构造函数/其他方法中,您可以调用上述方法,如下所示:
public Student(String name, String age)
{
this.name = name;
this.age = age;
addStudent(this); //here is the call to the above method
}
关于java - 在没有硬编码参数的情况下调用构造函数(耦合),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19525188/