Home > Blockchain >  Why is the constructor not accepted?
Why is the constructor not accepted?

Time:07-16

The instructions are The Bullet class's constructor must initialize the dy field to -1 if the constructor's direction parameter is equal to Direction.UP.
The Bullet class's constructor must initialize the dy field to 1 if the constructor's direction parameter is not equal to Direction.UP.

My solution was

public Bullet(double x, double y, Direction direction) {
        super(x, y);
        setMatrix(ShapeMatrix.BULLET);
    if (Direction direction  == Direction.UP) {
        dy = -1;
    } else {
        dy = 1;
    }

But the correct solution was

    public Bullet(double x, double y, Direction direction) {
        super(x, y);
        setMatrix(ShapeMatrix.BULLET);
        this.dy = direction == Direction.UP ? -1 : 1;
    }

Can someone explain to me why?

CodePudding user response:

this inside the constructor would refer to the new object being created and returned. In the first scenario :

 dy = -1;
 dy = 1;

these values are being created globally and attached to the window object. You ideally want them on your object and that is why this.dy works

CodePudding user response:

You need to use this to reference the object's properties. dy hasn't been defined in the constructor's scope.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes/constructor https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

CodePudding user response:

In your if statement, the Direction direction means you're initializing a variable

Just do if (direction == Direction.Up)

CodePudding user response:

You need to use this keyword when trying to access any class variables inside the constructor or any other function. Your code also works just access the dy property by this keyword only. Like the following

if (Direction direction  == Direction.UP) {
        this.dy = -1;
    } else {
        this.dy = 1;
    }

On the other hand in the provided solution is just that guy who just used the ternary operator as a shorthand of if else block nothing else.

Dont forget to up vote if you liked my answer.

  • Related