WizKid22
WizKid22

Reputation: 23

Am I using the 'this' keyword properly in my code?

I am looking for some guidance on the this keyword. I just learned about the concept and it is sort of confusing to me. Here is a piece of my code:

public class CashRegister {
    private ArrayList<Double> items;
    private int itemCount;
    private double totalPrice;

        public double getTotal() {
            this.totalPrice = 0;
            for (int i = 0; i < this.items.size(); i++) {
                this.totalPrice = this.totalPrice + this.items.get(i);
            }
            return totalPrice;
        }
    }

My question is if am I using 'this' right? Should I use 'this' every time I use a variable like totalPrice or the items ArrayList?

Upvotes: 1

Views: 81

Answers (3)

slickset
slickset

Reputation: 179

Generally, the most common usage of "this" is in object constructors. So you could have some thing like...

public NewThing(int count, double price) {
    this.count = count;
    this.price = price;
}

So it's mostly used to identify the object with which you're assigning the arguments that are being passed in. Because the variable names are the same as the arguments, "this" signals that it is "this object" receiving those attributes.

Upvotes: 1

wleao
wleao

Reputation: 2346

It's not wrong. But it's polluting the code because it's redundant. We all know that items and totalPrice are fields of the current object (referenced by this).

Here is a piece of code in which this makes sense:

public class Test {
    private String test;

    public Test(String test) {
        this.test = test;
    }
}

You may see that the reference to test is ambiguous. Inside the constructor if you just use test you won't know if you are accessing the field of the object of type Test or the reference String that was passed to the constructor, in this case you will be accessing the reference. So this is used to make sure you're using the field of the object of type Test.

There is a concept called shadowing. Using this is helpful to not fall in this trap of thinking that you're referencing something when you aren't.

this question is helpful: What is variable shadowing used for in a Java class?

Upvotes: 2

Mureinik
Mureinik

Reputation: 311808

The way you use this is definitely not wrong, but is redundant. You could write the same code without the thises and get the same result.

Upvotes: 1

Related Questions