【发布时间】:2010-11-20 14:28:10
【问题描述】:
在类构造函数中,我尝试使用:
if(theObject != null)
this = theObject;
我搜索数据库,如果记录存在,我使用 Hibernate Query 生成的theObject。
为什么我不能使用this?
【问题讨论】:
在类构造函数中,我尝试使用:
if(theObject != null)
this = theObject;
我搜索数据库,如果记录存在,我使用 Hibernate Query 生成的theObject。
为什么我不能使用this?
【问题讨论】:
这是因为“this”不是变量。它指的是当前参考。如果允许您重新分配“this”,它将不再是“this”,而是“that”。你不能这样做。
【讨论】:
this 不是变量,而是值。您不能将 this 作为表达式中的左值。
【讨论】:
this 表示一个值,它是对其调用实例方法的对象的引用”。见java.sun.com/docs/books/jls/third_edition/html/…
因为你不能分配给this。
this 代表当前对象实例,即你自己。您可以将this 视为对其代码当前正在执行的对象实例的不可变引用。
【讨论】:
“this”是指调用你的方法的对象实例。
【讨论】:
this关键字持有当前对象的引用。我们举个例子来理解。
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;
}
}
在上面的例子中有一个类名ThisKeywordExample,它由两个实例数据成员a和b组成。 有一个 add 方法,它首先将数字设置到 a 和 b 然后返回 addtion。
实例数据成员在我们创建该类的对象并被 我们持有该对象的引用。在上面的例子中,我们在 main 方法中创建了类的对象并持有 该对象的引用到 tke 引用变量中。当我们调用 add 方法时,如何在 add 方法中访问 a 和 b 因为add方法没有对象的引用。这个问题的答案清楚了this关键字的概念
上面的代码被JVM当作
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;
}
}
上述更改由 JVM 完成,因此它会自动将另一个参数(对象引用)传递给方法并 将它保存到引用变量 this 中并访问该对象的实例成员 throw this 变量。
上面的改动是由 JVM 完成的,如果你要编译代码,那么就会出现编译错误,因为你什么都不用做。All 这由 JVM 处理。
【讨论】: