Using java is the keyword

In the class constructor, I am trying to use:

if(theObject != null) this = theObject; 

I am looking for a database, and if the record exists, I use theObject generated by Hibernate Query.

Why can't I use this ?

+7
java this
source share
5 answers

this not a variable, but a value. You cannot have this as an lvalue in an expression.

+5
source share

This is because 'this' is not a variable. This refers to the current link. If you are allowed to reassign 'this', it will no longer remain 'this', it will become 'this'. You cannot do this.

+15
source share

Because you cannot assign this .

this represents the current instance of the object, that is, independently. You can think of this as an immutable reference to an instance of the object whose code is currently executing.

+3
source share

"this" refers to the instance of the object in which you are calling the method.

+1
source share

this keyword holds the link of the current object. Let's take an example to understand it.

 class ThisKeywordExample { int a; int b; public static void main(String[] args) { ThisKeywordExample tke=new ThisKeywordExample(); System.out.println(tke.add(10,20)); } int add(int x,int y) { a=x; b=y; return a+b; } } 

In the above example, there is a class name ThisKeywordExample, consisting of two data instances a and b. there is an add method that first sets the number to a and b, and then returns the add.

Instance data elements take memory when we create an object of this class and join the refrence variable into which we hold the refrence of this object. In the above example, we created a class object in the main method and held the refrence of this object to the tke refrence variable. when we call the add method, a and b are available in the add method because the add method does not have an object reference. The answer to this question will clear the concept of this keyword.

the above code is treated by the JVM as

  class ThisKeywordExample { int a; int b; public static void main(String[] args) { ThisKeywordExample tke=new ThisKeywordExample(); System.out.println(tke.add(10,20,tke)); } int add(int x,int y,ThisKeywordExample this) { this.a=x; this.b=y; return this.a+this.b; } } 

the above changes are performed by the JVM, so it automatically passes another parameter (object refrence) to the method and hold it in the refrence variable and get access to the instance element of this object to pass this variable.

The above changes are performed by the JVM, if you compile the code, then there is a compilation error because you do not have to do anything about it. This is handled by the JVM.

+1
source share

All Articles