1.this关键字只能在方法内部使用,表示对“调用方法的那个对象”的引用。
2.this关键字的使用:只有需要明确指出对当前对象的引用时,才需要用该关键字,不要在不必要的地方使用,会造成混乱。eg:
例如,一个外部的工具方法,实现了给苹果削皮的功能:先传入一个苹果,再返回这个削过皮的苹果。
[b]类调用非静态方法的时候,会把当前实例做为一个参数传入函数,这个参数在函数里命名为this。 是被系统隐含使用的。而静态方法,this是不传的。[/b]
2.this关键字的使用:只有需要明确指出对当前对象的引用时,才需要用该关键字,不要在不必要的地方使用,会造成混乱。eg:
public class User {
public User increment()
{
return this;//返回调用该方法的那个实例
}
}
例如,一个外部的工具方法,实现了给苹果削皮的功能:先传入一个苹果,再返回这个削过皮的苹果。
//工具类:
public class peeler
{
static Apple peel(Apple apple)
{
//remove peel
return apple; //peeled
}
}
//苹果类:
public class Apple
{
Apple getPeeled(){return peeler.peel(this);}//返回了调用该方法的对象
}
//person类:
piblic Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
System.out.println("over");
}
}
public class PassingThis(){
public static void main(String[] arges){
new Person().eat(new Apple());
}
}
[b]类调用非静态方法的时候,会把当前实例做为一个参数传入函数,这个参数在函数里命名为this。 是被系统隐含使用的。而静态方法,this是不传的。[/b]