Java - When to Use 'This' Keyword

Java - when to use 'this' keyword

but Java is clever enough to know what is happening if I change the statement in the constructor to

  bar = bar;

FALSE! It compiles but it doesn't do what you think it does!

As to when to use it, a lot of it is personal preference. I like to use this in my public methods, even when it's unnecessary, because that's where the interfacing happens and it's nice to assert what's mine and what's not.

As reference, you can check the Oracle's Java Tutorials out about this.subject ;-)

http://docs.oracle.com/javase/tutorial/java/javaOO/thiskey.html

Use of this keyword in java

this is an alias or a name for the current instance inside the instance. It is useful for disambiguating instance variables from locals (including parameters), but it can be used by itself to simply refer to member variables and methods, invoke other constructor overloads, or simply to refer to the instance. Some examples of applicable uses (not exhaustive):

class Foo
{
private int bar;

public Foo() {
this(42); // invoke parameterized constructor
}

public Foo(int bar) {
this.bar = bar; // disambiguate
}

public void frob() {
this.baz(); // used "just because"
}

private void baz() {
System.out.println("whatever");
}

}

Why is the using of 'this' keyword necessary?

What advantage does it have over passing the object itself since the
method is going to access the current object that is being passes
anyway.

As per your question on advantage of using this keyword over passing the object itself is this is a final variable in Java whereas the object when passed may or may not be final. Being a final variable, I can clearly see 2 main advantages of using this over passing object itself.

  1. One cannot assign any new value to the current instance of this.

    this = new Foo(); //compilation error; cannot assign value to final variable : this

  2. It can be used in synchronized block.

    synchronized(this){
    /*this synchronized block will be locked on current instance*/
    }

Apart from this context set up in the question, there are many advantages of using this in Java which you can figure out from other answers.

Shishir

Should I use this keyword when I want to refer to instance variables within a method?

No, only use this when you have a name conflict such as when a method parameter has the same name as an instance field that it is setting.

It can be used at other times, but many of us feel that it simply adds unnecessary verbiage to the code.

Why isn't the this keyword working in this constructor?

Your first example does not work because the fields you are trying to assign, cName, courseNum, and mod, are not declared in the class. You need to declare the fields in order for the assignments to work. Make the variables private to make sure that they are well encapsulated:

public Course {
private String cName;
public Course(String cName) {
this.cName = cName;
}
}

The reason you need to use this is to disambiguate between cName-the-parameter and cName-the-instance-variable. You could disambiguate in some other way - for example, by renaming one of the variables:

public Course {
private String cName;
public Course(String name) {
cName = name; // Using "this" is no longer required,
// because names are different.
}
}

when using this keyword inside method or constructor, does it matter the this keyword is on the left or the right of = sign

It does indeed matter. In Java the variable on the left is receiving the value of the variable on the right.

So in your example:

class Point {

public int x = 0; // line 1
public int y = 0; // line 2

public Point(int x, int y) { // line 3
x = this.x; // line 4
this.y = y; // line 5
}
}

x =this.x is saying "take the value of x from line 1 and put that value into the x from line 3. so here your parameter x which was passed in (line 3) to create your object will now be set equal to 0 (because that's what created on line 1). This is probably not what you want.

this.y = y is saying "take the value from the y parameter passed in (line 3) and put that value into the y created on line 2. so your parameter y that was passed in will overwrite the 0 that you instantiated your y variable to on line 2.

One tip for remembering this that I learnt back in college was to think of the = as an arrow that always points to the left/receiver.

Therefore you have:

x <--- this.x (note the direction the arrow is going)

this.y <--- y (the left is always the the receiver of the value)

Finally, I would suggest that you don't get too caught up in the code and remember to always think of the bigger picture.

You are creating a class named Point.

Why? Because you need an object to use.

What do you need to create this object? X and Y coordinates.

Would your class know these automatically? No, therefore they are being passed in as constructor parameters.

Now that you have them, how do you get the rest of the members (i.e other methods/variables) of your class to know they are there? You have to assign their values to something that this class/object will know about. And that is why you use the this keyword.

Hope this helps. Stick with it. You'll get better with time. ;-)



Related Topics



Leave a reply



Submit