简体   繁体   English

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

[英]What is the difference between Class.this and this in 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;
  }
}

One uses this.name to reference the object field, but the other uses className.this to reference the object field. 一个使用this.name引用对象字段,但另一个使用className.this引用对象字段。 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.this语法很有用。

class Person{
    String name;

    public void setName(String name){
        this.name = name;
    }

    class Displayer {
        String getPersonName() { 
            return Person.this.name; 
        }

    }
}

This syntax only becomes relevant when you have nested classes: 只有嵌套类时,此语法才会变得相关:

class Outer{
    String data = "Out!";

    public class Inner{
        String data = "In!";

        public String getOuterData(){
            return Outer.this.data; // will return "Out!"
        }
    }
}

You only need to use className.this for inner classes. 您只需要将className.this用于内部类。 If you're not using them, don't worry about it. 如果您不使用它们,请不要担心。

Class.this is useful to reference a not static OuterClass . Class.this是有用的引用不是一成不变的OuterClass

To instantiate a nonstatic InnerClass , you must first instantiate the OuterClass . 为了实例化一个非静态InnerClass ,必须先初始化OuterClass Hence a nonstatic InnerClass will always have a reference of its OuterClass and all the fields and methods of OuterClass is available to the InnerClass . 因此,一个非静态InnerClass总会有其参考OuterClass和所有的领域和方法OuterClass是提供给InnerClass

public static void main(String[] args) {

        OuterClass outer_instance = new OuterClass();
        OuterClass.InnerClass inner_instance1 = outer_instance.new InnerClass();
        OuterClass.InnerClass inner_instance2 = outer_instance.new InnerClass();
        ...
}

In this example both Innerclass are instantiated from the same Outerclass hence they both have the same reference to the Outerclass . 在该示例中两个Innerclass是由相同的实例化Outerclass因此它们都具有相同的参考Outerclass

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM