this的使用

来源:百度知道 编辑:UC知道 时间:2024/05/06 04:46:07
class Leaf
{
Leaf increment()
{
return this;
}

public static void main(String args[])
{
Leaf lf=new Leaf();
System.out.println(lf.increment());
}
}
结果: Leaf@de6ced
请问这个this是什么意思,顺便解释一下结果,当用类名直接调用increment()方法输入时提示无法从静态上下文中引用非静态方法,为什么类对象可以直接调用?
从网速copy的答案就不要啦,谢谢!

这个this是返回这个类,你既然实例化了Leaf,当然可以用对象.方法了。
你输出lf.increment() 和输出 lf的结果是一样的,。打印的都是Leaf类的地址

//对程序做了小小的修改,便于说明 好好看看吧

public class Leaf {

String name;

public Leaf() {

}

public Leaf(String name){
this.name = name;
}
//把调用该increment()的对象返回
Leaf increment() {
System.out.println("调用了" + name + "的increment()");
return this;
}
//声明为静态就可通过类名调用
static Leaf grow() {
return new Leaf("来自static");
}

public void introduce(){
System.out.println("我现在是" + this.name + "了");
}

public static void main(String args[]) {
Leaf lf1 = new Leaf("叶子一");
lf1.introduce();
Leaf lf2 = new Leaf("叶子二");
lf2.introduce();
lf1 = lf2.increment();//lf2调用了increment(),所以把lf2的句柄返回,并付给lf1,lf1,lf2指向 同一块内容
lf1.introduce();
lf2.introduce();