人员类别:

public class Person {


    private String firstName;
    private String lastName;

    public Person(String firstname,String lastname) throws InvalidDataException
    {
        setFirstname( firstname);
        setLastname(lastname);
    }


    public void personFirstName(String firstName) throws InvalidDataException {
        setFirstname(firstName);
    }

    public void personLastName(String lastname) throws InvalidDataException {

        setLastname(lastname);
    }

    public String getFirstName() {
        return firstName;
    }

    public String getlasttName()
    {
        return lastName;
    }

    protected final void setFirstname(String firstname) throws InvalidDataException{
         if( firstname == null ||firstname.length() < 1) {
                throw new InvalidDataException("First Name Cannot be Empty");
         }
          this.firstName=firstname;

    }

    protected final void setLastname(String lastname) throws InvalidDataException {

         if( lastname == null ||lastname.length() < 1) {
                throw new InvalidDataException("Last Name Cannot be Empty");

         }

         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
        setProfessorID(professorID);
    }

    public void setID(String professorID) throws InvalidDataException{

        setProfessorID(professorID);
    }

    public String getID()
    {
        return this.professorID;
    }

    private void setProfessorID(String ID) throws InvalidDataException{
         if( ID == null ||ID.length() < 1) {
                throw new InvalidDataException("ID Cannot be Empty");
         }
          this.professorID=ID;

    }

    public void printData()
    {
         System.out.println("Professor ID: " + this.getID() + " First Name: " + this.getFirstName() + " Last Name: " + this.getlasttName());
    }

}


我已经完成了一些关于实现setter并在子类中调用它们的研究。通过声明它们是受保护的和最终的,我防止子类重写它并进行有害的行为。我的问题是,我现在可以摆脱personFirstName()和personLastName()吗?我的构造函数不使用它,而是调用受保护的最终setFirstname和setLastname()。摆脱公众的影响会在以后的发展中引起问题吗?

最佳答案

您已经说过,您的目标是避免在构造函数中调用可能被子类覆盖的方法。如果是这样,我会这样处理:

public Person(String firstName, String lastName) {
    this.privateSetFirstName(firstName);
    this.privateSetLastName(lastName);
}
private void privateSetFirstName(String firstName) {
    // ...your logic for setting the field...
}
private void privateSetLastName(String lastName) {
    // ...your logic for setting the field...
}
public void setFirstName(String firstName) {
    this.privateSetFirstName(firstName);
}
public void setLastName(String lastName) {
    this.privateSetLastName(lastName);
}


例如,将标准设置器设为标准,并在实现内的私有方法中保留特定于实现的详细信息。

10-01 17:56