public class Player{private String firstName;private String lastName;private int heightInInches;private double weightInPounds;private boolean goalScorer;private boolean drinksBeer;public Player(){}public Player(String firstName, String lastName, int heightInInches, double weightInPounds, boolean goalScorer, boolean drinksBeer){ if(lastName != null && lastName.trim().length() > 0){ if(lastName != null && lastName.trim().length() > 0){ if(heightInInches >= 0){ if(weightInPounds >= 0){ this.firstName = firstName; this.lastName = lastName; this.heightInInches = heightInInches; this.weightInPounds = weightInPounds; this.goalScorer = goalScorer; this.drinksBeer = drinksBeer; } } } }}public String getFirstName(){ return firstName;}public String getLastName(){ return lastName;}public int getHeightInInches(){ return heightInInches;}public double getWeightInPounds(){ return weightInPounds;}public boolean getGoalScorer(){ return goalScorer;}public boolean getDrinksBeer(){ return drinksBeer;}public void setFirstName(String firstName){ if(firstName != null && firstName.trim().length() > 0){ this.firstName = firstName; }else{ System.out.println("Error. Invalid First Name."); }}public void setLastName(String lastName){ if(lastName != null && lastName.trim().length() > 0){ this.lastName = lastName; }else{ System.out.println("Error. Invalid Last Name."); }}在重载的构造函数中,如何不使用赋值语句为每个字段调用 mutator 方法?并且如果我调用 mutator 方法,我应该删除构造函数中的 if 语句吗?(我使用的是blueJ)我是初学者,所以请说明我的代码中是否还有其他问题。提前致谢。
1 回答
函数式编程
TA贡献1807条经验 获得超9个赞
您所要做的就是像任何其他方法一样引用 mutator 方法:
public Player(String firstName, String lastName, int heightInInches, double weightInPounds, boolean goalScorer, boolean drinksBeer) { setFirstName(firstName); setLastName(lastName); setHeightInInches(heightInInches); setWeightInPounds(weightInPounds); setGoalScorer(goalScorer); setDrinksBeer(drinksBeer);}
此外,不需要那些 if 语句,因为它们实际上并没有做任何有用的事情。如果您没有明确设置任何值,int
变量将默认为0
、double
默认为0.0
、boolean
默认为false
、String
默认为null
。因此,您的 if 语句正在执行诸如“如果名字是null
,请不要设置它……所以null
无论如何它都会默认”之类的事情。
如果你想做一些事情,比如强制高度为正数,你总是可以把这个逻辑放在 setter 中。
添加回答
举报
0/150
提交
取消