Skip to content
Advertisement

Using ‘this’ in constructor and other methods in Java – when is it OK to skip it?

I’m new to Java, so forgive me if it’s a stupid question. I tried to find a clear answer on this forum but with no joy.

I know what ‘this’ is. It know it refers to an actual instance and helps narrow the context when targeting a variable, but I found that it is possible to execute the code without any issues despite not using ‘this’ phrase. Turns out it depends on how you name your parameters when you declare methods. As you can see below, code returns ‘null’ if my parameter is named the same as the state I’m initialising/modifying.

This works only in the class where the variables are declared. You’d still have to use ‘this’ in any sub-class, if it tried to access/modify a variable declared in its parent class.

Now, would this be considered incorrect and should it be avoided even though it seems to be working fine?

Thanks!

JavaScript

Output:

JavaScript

Advertisement

Answer

I think you should read official documantation about “this” keyword.

Using this with a Field The most common reason for using the this keyword is because a field is shadowed by a method or constructor parameter.

For example, the Point class was written like this

JavaScript

but it could have been written like this:

JavaScript

Each argument to the constructor shadows one of the object’s fields — inside the constructor x is a local copy of the constructor’s first argument. To refer to the Point field x, the constructor must use this.x.

About you question:

Now, would this be considered incorrect and should it be avoided even though it seems to be working fine?

It is depends for code style do yoy have in your projects or teams. Technically, both ways are possible and correct, using name = newName is shorter, and using this.name = name is more safe to avoid mistakes.

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement