猿问

java - 如何在重载的构造函数中调用mutator方法而不是在java中分配它们?

 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)我是初学者,所以请说明我的代码中是否还有其他问题。提前致谢。


吃鸡游戏
浏览 114回答 1
1回答

函数式编程

您所要做的就是像任何其他方法一样引用 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 中。
随时随地看视频慕课网APP

相关分类

Java
我要回答