正如你可以看到下面的类声明2私有实例变量和2得到& 2设置方法与每个私人成员关联,以允许对它们进行操作和验证。良好的软件实践 - 获取和设置方法
我的问题是:哪个更适合在构造函数的减速中使用,实例变量直接如下面的代码片段所示,或者使用与它们相关联的set方法,以及哪些是在toString中使用的良好软件实践方法,实例变量或他们的getter方法?
谢谢你的时间。
public Class Employee {
private String firstName;
private String lastName;
public Employee (String first, String last)
{
firstName = first;
lastName = last;
}//end of constructor
public void setFirstName(String first)
{
firstName = first;
}//end of method setFirstName
public String getFirstName()
{
return firstName;
}
public void setLastName(String last)
{
lastName = last;
}//end of method setLastName
public String getLastName()
{
return lastName;
}//end of method getLastName
public String toString()
{
return String.format ("%s: %s %s\n", "Employee Name: ", firstName, lastName);
}//end of method toString
}//end of class Employee
除此之外,作为一个经验法则,在构造函数中使用可重写的方法是不鼓励的,因为它使代码完全无法维护(至少在我遇到过的情况下)。 – fjdumont 2012-03-28 14:59:09
谢谢布赖恩的时间和解释。这是有帮助的。 – Sinan 2012-03-28 15:03:09