java class和this,Class.this和Java之间有什么区别

本文解释了在Java中,如何通过`this.name`和`ClassName.this.name`两种方式在类内部引用同一对象字段,并指出在给定例子中它们其实等效。特别关注了当嵌套非静态类需要引用外部类实例时,Class.this的用法。

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

There are two ways to reference the instance of a class within that class. For example:

class Person {

String name;

public void setName(String name) {

this.name = name;

}

public void setName2(String name) {

Person.this.name = name;

}

}

One uses this.name to reference the object field, but the other uses className.this to reference the object field. What is the difference between these two references?

解决方案

In this case, they are the same. The Class.this syntax is useful when you have a non-static nested class that needs to refer to its outer class's instance.

class Person{

String name;

public void setName(String name){

this.name = name;

}

class Displayer {

String getPersonName() {

return Person.this.name;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值