班级最佳实践

sca*_*cci 21 java

如果我有一个带有重载构造函数的客户类(默认值和带有params的客户类),在Overloaded构造函数中设置类成员的正确方法是什么?使用"this"引用还是使用setter方法?

只是不确定适当的方法是什么.

public class Customer {

private String firstName;
private String lastName;
private int age;

public Customer() {}

//This Way
public Customer(String firstName, String lastName, int age)
{
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
}

// Or this way?
  public Customer(String firstName, String lastName, int age)
{
    setFirstName(firstName); 
    setLastName(lastName);
    setAge(age);
}



/**
 * @return the firstName
 */
public String getFirstName() {
    return firstName;
}

/**
 * @param firstName the firstName to set
 */
public void setFirstName(String firstName) {
    this.firstName = firstName;
}

/**
 * @return the lastName
 */
public String getLastName() {
    return lastName;
}

/**
 * @param lastName the lastName to set
 */
public void setLastName(String lastName) {
    this.lastName = lastName;
}

/**
 * @return the age
 */
public int getAge() {
    return age;
}

/**
 * @param age the age to set
 */
public void setAge(int age) {
    this.age = age;
}
Run Code Online (Sandbox Code Playgroud)

}

Joe*_*e K 27

第一个(使用this.)可能更安全,更直接.考虑未来的子类是否会覆盖setter方法 - 这可能会导致非常意外的行为.

如果你的课程是最终的,这是无关紧要的,这是一个洗.

  • 到目前为止,这是唯一明智的答案.事实上,几个lint工具将警告从构造函数调用非final方法,因为正是这个问题.(如果该类不是最终的,但是setter方法是,它也同样好.) (4认同)