Java: Class.this

前端 未结 5 1211
野趣味
野趣味 2020-11-27 11:41

I have a Java program that looks like this.

public class LocalScreen {

   public void onMake() {
       aFuncCall(LocalScreen.this, oneString, twoString);
          


        
5条回答
  •  情话喂你
    2020-11-27 12:28

    Class.this allows access to instance of the outer class. See the following example.

    public class A
    {
      final String name;
      final B      b;
      A(String name) {
        this.name = name;
        this.b = new B(name + "-b");
      }
    
      class B
      {
        final String name;
        final C      c;
        B(String name) {
          this.name = name;
          this.c = new C(name + "-c");
        }
    
        class C
        {
          final String name;
          final D      d;
          C(String name) {
            this.name = name;
            this.d = new D(name + "-d");
          }
    
          class D
          {
            final String name;
            D(String name) {
              this.name = name;
            }
    
            void printMe()
            {
              System.out.println("D: " + D.this.name); // `this` of class D
              System.out.println("C: " + C.this.name); // `this` of class C
              System.out.println("B: " + B.this.name); // `this` of class B
              System.out.println("A: " + A.this.name); // `this` of class A
            }
          }
        }
      }
      static public void main(String ... args)
      {
        final A a = new A("a");
        a.b.c.d.printMe();
      }
    }

    Then you will get.

    D: a-b-c-d
    C: a-b-c
    B: a-b
    A: a

提交回复
热议问题