我已经创建了一个Person类,以及一个继承自它的类,即教授类。现在,我已经在Person课程和教授课程中声明了我的二传手。我希望构造函数通过调用setter并执行验证来设置变量。我做的正确吗?如果没有,我该怎么做才能纠正它?
人类:
public class Person {
private String firstName;
private String lastName;
public Person(String firstname,String lastname) throws InvalidDataException
{
setFirstName(firstname);
setLastName(lastname);
}
public String getFirstName() {
return firstName;
}
private void setFirstName(String firstName) throws InvalidDataException {
if ( firstName == null || firstName.length() < 1) {
throw new InvalidDataException("Person Must have First Name");}
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
private void setLastName(String lastName) throws InvalidDataException {
if ( lastName == null || lastName.length() < 1) {
throw new InvalidDataException("Person Must have Last Name");}
this.lastName = lastName;
}
教授班
public class Professor extends Person {
private String professorID;
public Professor(String professorID,String firstname, String lastname) throws InvalidDataException {
super(firstname, lastname);
// TODO Auto-generated constructor stub
this.setID(professorID);
}
private void setID(String professorID) throws InvalidDataException{
if ( professorID == null ||professorID.length() < 1) {
throw new InvalidDataException("Person Must have ID");}
this.professorID = professorID;
}
public String getID()
{
return this.professorID;
}
public void printData()
{
System.out.println("Professor ID: " + this.getID() + " First Name: " + this.getFirstName() + " Last Name: " + this.getLastName());
}
}
答案 0 :(得分:2)
考虑到你的“ setters ”主要检查字符串既不是空也不是空,你可能有一个静态或实用方法就是这样做,并在构造函数(和/或公共setter)中调用它)在分配给班级成员之前。
public class Person {
protected void check( String s, String msg ){
if( s == null ||s.length < 1) {
throw new InvalidDataException(msg);
}
}
public Person(String firstname,String lastname) throws InvalidDataException{
check( firstname, "Person's first name missing" );
check( lastname, "Person's last name missing" );
this.firstname = firstname;
this.lastname = lastname;
}
public void setFirstname( String firstname ){
check( firstname, "Person's first name missing" );
this.firstname = firstname;
}
}
但是豆子不应该需要这样的守卫。如果有GUI,GUI应该进行验证,只将正确的值传递给对象构造。
答案 1 :(得分:0)
将setter声明为private是一种不好的做法。因为setter的目标是从类实例中调用它们在该类之外。如果你真的想用构造函数填充你的类属性,你可以创建一个私有函数来构建你的类。 ** ps:如果你的类属性很容易填充,你可以在构造函数中填充它们。你不需要任何支持函数。
答案 2 :(得分:0)
最好的方法是将Person类成员设置为protected而不是private。 无论如何,定居者和吸气者应该在OOD公开。