Java什么时候用到this关键字_java中this关键字什么时候使用

本文详细介绍了Java中this关键字的四种常见应用场景:解决局部变量与成员变量重名问题、将当前对象作为参数传递给其他方法、从方法中返回当前对象的引用以及在构造器中调用其他构造器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

java中this关键字什么时候使用

d663f85b5883

1、当局部变量和成员变量重名的时候,在方法中使用this表示成员变量以示区分

实例:

classDemo{

String str = "这是成员变量";

void fun(String str){

System.out.println(str);

System.out.println(this.str);

this.str = str;

System.out.println(this.str);

}

}

publicclassThis{

publicstaticvoid main(String args[]){

Demo demo = newDemo();

demo.fun("这是局部变量");

}

}

2、this关键字把当前对象传递给其他方法

实例:

classPerson{

publicvoid eat(Apple apple){

Apple peeled = apple.getPeeled();

System.out.println("Yummy");

}

}

classPeeler{

staticApple peel(Apple apple){

//....remove peel

returnapple;

}

}

classApple{

Apple getPeeled(){

returnPeeler.peel(this);

}

}

publicclassThis{

publicstaticvoid main(String args[]){

newPerson().eat(newApple());

}

}

3、当需要返回当前对象的引用时,就常常在方法写return this

这种做法的好处是:当你使用一个对象调用该方法,该方法返回的是经过修改后的对象,且又能使用该对象做其他的操作。因此很容易对一个对象进行多次操作。

publicclassThis{

int i = 0;

This increment(){

i += 2;

returnthis;

}

void print(){

System.out.println("i = "+ i);

}

publicstaticvoid main(String args[]){

This x = newThis();

x.increment().increment().print();

}

}

结果为:4

4、在构造器中调用构造器需要使用this

一个类有许多构造函数,有时候想在一个构造函数中调用其他构造函数,以避免代码重复,可以使用this关键字。

d663f85b5883

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值