关于java里返回对象的引用

来源:百度知道 编辑:UC知道 时间:2024/09/20 20:51:27
public class Account {
private int accountId=100000;

public Account creatAccount()
{
accountId++;
return this;
}

public int getAccountId()
{
return accountId;
}

public static void main(String args[])
{
Account account =new Account();
System.out.println("帐号是:"
+account.getAccountId());
}

}

请问return this;这个this是指什么,如果改成return accountId;为什么是错的?
小弟刚初学java各位高人指点下小弟谢谢
那请问这个this是指什么呢?

return this
this是只当前对象,也就是哪个对象调用这个creatAccount()函数,this就指向哪个对象

public Account creatAccount()
{
accountId++;
return this;
}
你这个函数的返回类型是Account ,而accountId是int型的,返回当然会出错

accountId的数据类型不是Account

this 指代的是本类对象 即Account类 并不是谁调用creatAccount()方法就指代谁。