Usage of Java this keyword

2019-01-24 11:35发布

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?

标签: java this
5条回答
一纸荒年 Trace。
2楼-- · 2019-01-24 12:04

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.

查看更多
ゆ 、 Hurt°
3楼-- · 2019-01-24 12:09

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

查看更多
劫难
4楼-- · 2019-01-24 12:19

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.

查看更多
神经病院院长
5楼-- · 2019-01-24 12:25

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

查看更多
霸刀☆藐视天下
6楼-- · 2019-01-24 12:25

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.

查看更多
登录 后发表回答