版权声明
1. 本站文章和资源均来自互联网收集和整理,本站不承担任何责任及版权问题。
2. 相关版权归作者及其公司所有,仅供学习研究用途,请勿用于商业目的。
3. 若侵犯您的版权,请发邮件至webmaster@ishare1.cn联系我们,我们确认后将立即删除。

1、当局部变量和成员变量重名的时候,在方法中使用this表示成员变量以示区分
实例:
class Demo{
String str = "这是成员变量";
void fun(String str){
System.out.println(str);
System.out.println(this.str);
this.str = str;
System.out.println(this.str);
}
}
public class This{
public static void main(String args[]){
Demo demo = new Demo();
demo.fun("这是局部变量");
}
}
2、this关键字把当前对象传递给其他方法
实例:
class Person{
public void eat(Apple apple){
Apple peeled = apple.getPeeled();
System.out.println("Yummy");
}
}
class Peeler{
static Apple peel(Apple apple){
//....remove peel
return apple;
}
}
class Apple{
Apple getPeeled(){
return Peeler.peel(this);
}
}
public class This{
public static void main(String args[]){
new Person().eat(new Apple());
}
}
3、当需要返回当前对象的引用时,就常常在方法写return this
这种做法的好处是:当你使用一个对象调用该方法,该方法返回的是经过修改后的对象,且又能使用该对象做其他的操作。因此很容易对一个对象进行多次操作。
public class This{
int i = 0;
This increment(){
i += 2;
return this;
}
void print(){
System.out.println("i = " + i);
}
public static void main(String args[]){
This x = new This();
x.increment().increment().print();
}
}
结果为:4
4、在构造器中调用构造器需要使用this
一个类有许多构造函数,有时候想在一个构造函数中调用其他构造函数,以避免代码重复,可以使用this关键字。

推荐教程:Java教程
什么是this? this是自身的一个对象,代表对象本身,可以理解为:指向对象本身的一个指针。 用法如下: 用”this.成员变量名称”和重名的局部变量区分开来; 用”this.成员方法名”访问成员方法。 class Person{ private Strin…
爱分享




