What is the meaning of "this" in Java?

Viewed 458863

Normally, I use this in constructors only.

I understand that it is used to identify the parameter variable (by using this.something), if it have a same name with a global variable.

However, I don't know that what the real meaning of this is in Java and what will happen if I use this without dot (.).

22 Answers

Instance variables are common to every object that you creating. say, there is two instance variables

class ExpThisKeyWord{
int x;
int y;

public void setMyInstanceValues(int a, int b) {
    x= a;
    y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

}




class Demo{
public static void main(String[] args){

ExpThisKeyWord obj1 = new ExpThisKeyWord();
ExpThisKeyWord obj2 = new ExpThisKeyWord();
ExpThisKeyWord obj3 = new ExpThisKeyWord();

obj1.setMyInstanceValues(1, 2);
obj2.setMyInstanceValues(11, 22);
obj3.setMyInstanceValues(111, 222);



}
}

if you noticed above code, we have initiated three objects and three objects are calling SetMyInstanceValues method. How do you think JVM correctly assign the values for every object? there is the trick, JVM will not see this code how it is showed above. instead of that, it will see like below code;

public void setMyInstanceValues(int a, int b) {
    this.x= a; //Answer: this keyword denotes the current object that is handled by JVM.
    this.y=b;

    System.out.println("x is ="+x);
    System.out.println("y is ="+y);
}

(I know Im late but shh Im being the sneaky boi you never saw me)

The this keyword in most Object Oriented programming languages if not all means that its a reference towards the current object instance of that class. It's essentially the same thing as calling on that object from outside of the method by name. That probably made no sense so Ill elaborate:

Outside of the class, in order to call something within that instance of the object, for example a say you have an object called object and you want to get a field you would need to use

object.field

Say for instance you are trying to access object.field from inside of your class in say, your constructor for example, you could use

this.field

The this keyword essentially replaces the object name keyword when being called inside of the class. There usually isn't much of a reason to do this outside of if you have two variables of the same name one of which being a field of the class and the other just being a variable inside of a method, it helps decipher between the two. For example if you have this: (Hah, get it? this? Hehe .... just me? okay :( I'll leave now)

public String Name;
//Constructor for {object} class
public object(String Name){
    Name = Name;
}

That would cause some problems, the compiler wouldn't be able to know the difference between the Name variable defined in the parameters for the constructor and the Name variable inside of your class' field declarations so it would instead assign the Name parameter to.... the value of the Name parameter which does nothing beneficial and literally has no purpose. This is a common issue that most newer programs do and I was a victim of as well. Anyways, the correct way to define this parameter would be to use:

public String Name;
//Constructor for {object} class
public object(String Name){
    this.Name = Name;
}

This way, the compiler knows the Name variable you are trying to assign is a part of the class and not a part of the method and assigns it correctly, meaning it assigns the Name field to whatever you put into the constructor.

To sum it up, it essentially references a field of the object instance of the class you are working on, hence it being the keyword "this", meaning its this object, or this instance. Its a good practice to use this when calling a field of your class rather than just using the name to avoid possible bugs that are difficult to find as the compiler runs right over them.

This refers to the object you’re “in” right now. In other words,this refers to the receiving object. You use this to clarify which variable you’re referring to.Java_whitepaper page :37

class Point extends Object
{
    public double x;
    public double y;

    Point()
    {
        x = 0.0;
        y = 0.0;
    }

    Point(double x, double y)
    {
        this.x = x;
        this.y = y;
    }
}

In the above example code this.x/this.y refers to current class that is Point class x and y variables where (double x,double y) are double values passed from different class to assign values to current class .

In Java "this" is a predefined variable. If we use "this" in method that's mean we are getting the reference (address) of the currently running object. For an example.

this.age ---> age of the currently running object.

I would like to share what I understood from this keyword. This keyword has 6 usages in java as follows:-

1. It can be used to refer to the current class variable. Let us understand with a code.*

Let's understand the problem if we don't use this keyword by the example given below:

class Employee{  
int id_no;  
String name;  
float salary;  
Student(int id_no,String name,float salary){  
id_no = id_no;  
name=name;  
salary = salary;  
}  
void display(){System.out.println(id_no +" "+name+" "+ salary);}  
}  
class TestThis1{  
public static void main(String args[]){  
Employee s1=new Employee(111,"ankit",5000f);  
Employee s2=new Employee(112,"sumit",6000f);  
s1.display();  
s2.display();  
}}  

Output:-

0 null 0.0
0 null 0.0

In the above example, parameters (formal arguments) and instance variables are same. So, we are using this keyword to distinguish local variable and instance variable.

class Employee{  
int id_no;  
String name;  
float salary;  
Student(int id_no,String name,float salary){  
this.id_no = id_no;  
this.name=name;  
this.salary = salary;  
}  
void display(){System.out.println(id_no +" "+name+" "+ salary);}  
}  
class TestThis1{  
public static void main(String args[]){  
Employee s1=new Employee(111,"ankit",5000f);  
Employee s2=new Employee(112,"sumit",6000f);  
s1.display();  
s2.display();  
}} 

output:

111 ankit 5000
112 sumit 6000

2. To invoke the current class method.

class A{  
void m(){System.out.println("hello Mandy");}  
void n(){  
System.out.println("hello Natasha");  
//m();//same as this.m()  
this.m();  
}  
}  
class TestThis4{  
public static void main(String args[]){  
A a=new A();  
a.n();  
}}  

Output:

hello Natasha
hello Mandy

3. to invoke the current class constructor. It is used to constructor chaining.

class A{  
A(){System.out.println("hello ABCD");}  
A(int x){  
this();  
System.out.println(x);  
}  
}  
class TestThis5{  
public static void main(String args[]){  
A a=new A(10);  
}}

Output:

hello ABCD
10

4. to pass as an argument in the method.

class S2{  
  void m(S2 obj){  
  System.out.println("The method is invoked");  
  }  
  void p(){  
  m(this);  
  }  
  public static void main(String args[]){  
  S2 s1 = new S2();  
  s1.p();  
  }  
}  

Output:

The method is invoked

5. to pass as an argument in the constructor call

class B{  
  A4 obj;  
  B(A4 obj){  
    this.obj=obj;  
  }  
  void display(){  
    System.out.println(obj.data);//using data member of A4 class  
  }  
}  

class A4{  
  int data=10;  
  A4(){  
   B b=new B(this);  
   b.display();  
  }  
  public static void main(String args[]){  
   A4 a=new A4();  
  }  
} 

Output:-

10

6. to return current class instance

class A{  
A getA(){  
return this;  
}  
void msg(){System.out.println("Hello");}  
}  
class Test1{  
public static void main(String args[]){  
new A().getA().msg();  
}  
}  

Output:-

Hello

Also, this keyword cannot be used without .(dot) as it's syntax is invalid.

As everyone said, this represents the current object / current instance. I understand it this way, if its just "this" - it returns class object, in below ex: Dog if it has this.something, something is a method in that class or a variable

class Dog {
private String breed;
private String name;

Dog(String breed, String name) {
    this.breed = breed;
    this.name = name;
}

public Dog getDog() {
    // return Dog type
    return this;
}

}

enter image description here

The expression this always refers to the current instance.

  • In case of constructors, the current instance is the freshly allocated object that's currently being constructed.
  • In case of methods, the current instance is the instance on which you have called the method.

So, if you have a class C with some method m, then

  • during the construction of a fresh instance x of C, the this inside of the constructor will refer to x.
  • When x is an instance of C, and you invoke x.m(), then within the body of m, this will refer to the instance x.

Here is a code snippet that demonstrates both cases:

public class Example {
    static class C {
        public C whatDoesThisInConstructorReferTo;
        public C() {
            whatDoesThisInConstructorReferTo = this;
        }
        public C whatDoesThisInMethodReferTo() {
            return this;
        }
    }
    public static void main(String args[]) {
      C x = new C();
      System.out.println(x.whatDoesThisInConstructorReferTo == x); // true
      System.out.println(x.whatDoesThisInMethodReferTo() == x);    // true
    }
}

Regarding other syntactical elements that are unrelated to the this-expression:

  • The . is just the ordinary member access, it works in exactly the same way as in all other circumstances, nothing special is happening in case of this.
  • The this(...) (with round parentheses) is a special syntax for constructor invocation, not a reference.
Related