Usage of Java this keyword

人盡茶涼 提交于 2019-11-27 18:25:33

问题


In a class constructor, I am trying to use:

if(theObject != null)
    this = theObject; 

I search the database and if the record exists, I use theObject generated by Hibernate Query.

Why can't I use this?


回答1:


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




回答2:


It's because 'this' is not a variable. It refers to the current reference. If you were allowed to reassign 'this', it would no longer remain 'this', it would become 'that'. You cannot do this.




回答3:


Because you can't assign to this.

this represents the current object instance, i.e. yourself. You can consider this as an immutable reference to the object instance whose code is currently executing.




回答4:


"this" refers to the object instance in witch your method is being called from.




回答5:


this keyword hold the reference 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 which consist of two instance data member a and b. there is an add method which first set the number into the a and b then return the addtion.

Instance data members take the memory when we crete the object of that class and are accesed by the refrence variable in which we hold the refrence of that object. In the above example we created the object of the class in the main method and hold the refrence of that object into the tke refrence variable. when we call the add method how a and b is accessed in the add method because add method does not have the refrence of the object.The answer of this question 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 done by the JVM so it automatically pass the one more parameter(object refrence) into the method and hold it into the refrence variable this and access the instance member of that object throw this variable.

The above changes are done by JVM if you will compile code then there is compilation error because you have to do nothing in that.All this handled by the JVM.



来源:https://stackoverflow.com/questions/4233184/usage-of-java-this-keyword

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!