3

我有一个创建新对象 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 方法中进行硬编码?

4

3 回答 3

6

这样做:

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
}
于 2013-10-22T18:09:35.337 回答
4

您应该传递一个学生对象 - 而不是两个值。

public void addStudent(Student student)
{
     studentRegister.add(student);
}
于 2013-10-22T18:09:24.500 回答
0

使用

public void addStudent(final Student student) {
    studentRegister.add(student);
}

是更好的方法。

也许您正在寻找一种更简单的方法来构建对象。例如使用链式安装器:

public class Student {

    private String name;
    private String age;
    private String address;

    public String getName() {
        return name;
    }

    public Student setName(String name) {
        this.name = name;
        return this;
    }

    public String getAge() {
        return age;
    }

    public Student setAge(String age) {
        this.age = age;
        return this;
    }

    public String getAddress() {
        return address;
    }

    public Student setAddress(String address) {
        this.address = address;
        return this;
    }
}

那么,会:

Student student = new Student().setName("User")
                               .setAge("30")
                               .setAddress("New York");

使用普通设置器构建对象的另一种方法:

Student student = new Student(){{
    setName("User");
    setAge("30");
    setAddress("30");
}};
于 2013-10-22T18:21:47.937 回答