Class.this和Java之间有什么区别 [英] What is the difference between Class.this and this in Java

查看:144
本文介绍了Class.this和Java之间有什么区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有两种方法可以引用该类中的类实例。例如:

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;
  }
}

一个人使用 this.name 引用对象字段,但另一个使用 className.this 来引用对象字段。这两个引用之间有什么区别?

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?

推荐答案

在这种情况下,它们是相同的。当你有一个非静态嵌套类需要引用它的外部类的实例时, Class.this 语法很有用。

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; 
        }

    }
}

这篇关于Class.this和Java之间有什么区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆