quant
quant

Reputation: 512

How to handle constructors parameter properly

I am doing one of the online courses in Java and I have a bit of misunderstanding regarding Constructors parameter handling in this specific situation. The conditions are straight forward: if a value of a parameter that is passed while calling the constructor is less than 0, the field should have value 0; So, I am calling the constructor while creating a new object

       Test test = new Test(1.125, -1.0);

The first code sample works, and it does the job (x=1.125, y=0) but is this the right way of handling the parameter? (I have heard that it is not) It seems that I have actually changed the parameter first and not the field.

public class Test{
    private double x;
    private double y;

    public Test(double x, double y) {
        if(x < 0){
            x = 0;
        }
        if(y < 0){
            y = 0;
        }
        this.x = x;
        this.y = y;
    }
}

Then I have actually tried to change the field properly. Passing the same parameters while calling the constructor (1.125, -1.0).

public class Test{
    private double x;
    private double y;
        public Test(double x, double y) {
            if(x <= 0 && y >= 0){
                this.x = 0;
                this.y = y;
            }
            if(y <= 0 && x >= 0){
                this.y = 0;
                this.x = x;
            }
            if (x <= 0 && y <= 0){
                this.x = 0;
                this.y = 0;
            }
            else{
                this.x = x;
                this.y = y;
            }
    }
}

For some reason, constructor call set a field value for y to -1.0.

Why?

Didn't I exclude that with my expressions?

Upvotes: 1

Views: 85

Answers (1)

Islam Hassan
Islam Hassan

Reputation: 712

In the case you tried the code enters the else block of the following if-else:

if (x <= 0 && y <= 0)
{
    this.x = 0;
    this.y = 0;
}
else
{
    this.x = x;
    this.y = y;
}

thus overriding the value of y that was assigned by your second if statement. You should use if-else if...else across your code.

Upvotes: 3

Related Questions