gpt4 book ai didi

java - 类最佳实践

转载 作者:IT老高 更新时间:2023-10-28 20:46:29 25 4
gpt4 key购买 nike

如果我有一个带有重载构造函数的客户类(默认类和一个带有参数的类),那么在重载构造函数中设置类成员的正确方法是什么?使用“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;
}

}

最佳答案

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

如果你的类(class)是期末课,这无关紧要,只是洗刷。

关于java - 类最佳实践,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12324753/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com