gpt4 book ai didi

Java 重写 protected Setter 并消除公共(public) Setter

转载 作者:行者123 更新时间:2023-12-01 12:04:10 28 4
gpt4 key购买 nike

人员类别:

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;
}



}

教授类(class):

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 并在我的子类中调用它们的研究。通过声明它们是 protected 和最终的,我可以防止子类覆盖它并执行不需要的行为。我的问题是,我现在可以摆脱 personFirstName()personLastName() 吗?我的构造函数不使用它,它们调用 protected 最终 setFirstnamesetLastname()。摆脱公共(public) setter 会在以后的开发中引起问题吗?

最佳答案

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

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);
}

例如,使标准制定者成为标准,并将特定于实现的详细信息保留在实现中的私有(private)方法中。

关于Java 重写 protected Setter 并消除公共(public) Setter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27768571/

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