0

I am beginner in JAVA and I am totally confused with the definition of this in Java. I have read that it refers to the current object concerned.

But what does that mean ? Who assigns the object to this ? And how would I know while writing my code what should be the value of this at the moment.

In nutshell, I am totally confused with this. Can anyone help me in getting rid of my confusion ? I know that this is very useful.

Sean Patrick Floyd
  • 292,901
  • 67
  • 465
  • 588
Prashant Singh
  • 3,725
  • 12
  • 62
  • 106

5 Answers5

1

this is a keyword in Java which represents the object itself. This is covered in basics. Perhaps you can browse through any good articles on it. I am giving one from Oracle (formerly Sun Java tutorial)

Baz
  • 36,440
  • 11
  • 68
  • 94
sakthisundar
  • 3,278
  • 3
  • 16
  • 29
1

this is used to refrences variables in the class. For example

public class MyClass {
    private Integer i;

    public MyClass(Integer i) {
      this.i = i;
    }
}

In this code we are assigning the parameter i to the field i in the class. If you did not have the this then the parameter i would be assigned to itself. Usually you have different parameter names so you do not need this. For example

public class MyClass {
    private Integer i;

    public MyClass(Integer j) {
      this.i = j;
      //i = j; //this line does the same thing as the line above.
    }
}

In the above example you do not need this infront of the i

In summary you can use this to precede all your class fields. Most of the time you do not need to but if there is any sort of name shadowing then you can use this to explicitly say you are referring to a field.

You can also use this to refer to an object. It is used when you are dealing with inner classes and want to reference the outer class.

RNJ
  • 15,272
  • 18
  • 86
  • 131
1

This is simple.

The current object is the object whose code is running at the point. So, it is an instance of the class at which the this code appears.

In fact, unless you have the same identifier in object and local scope, this usually can be deleted and it will work exactly the same.

Example where you cannot delete this

public class myClass {
  private int myVariable;
  public setMyVariable(int myVariable) {
    this.myVariable = myVariable; // if you do not add this, the compiler won't know you are refering to the instance variable
  }
  public int getMyVariable() {
    return this.myVariable;  // here there is no possibility for confussion, you can delete this if you want
  }
}
SJuan76
  • 24,532
  • 6
  • 47
  • 87
-1

this refers to your current instance class. this is usually used for your accessors. E.g.:

public void Sample{
 private String name;

 public setName(String name){
  this.name = name;
 }
}

Notice that this was used to point specifically to the class Sample's variable name, instead of the parameter in the method setName.

Russell Gutierrez
  • 1,372
  • 8
  • 19