Anonymous classes containing instances

I am reading Joshua Blochs “Effective Java” 2nd Edition. I am currently in paragraph 22, which describes inner and nested classes, but I cannot understand what it means by this sentence:

Anonymous classes include instances if and only if they occur in a non-statistical context.

Can someone give me a code example and explain what exactly it does? I know that if it InnerClassis a member OuterClass, its spanning instance OuterClass, but in terms of an anonymous class, this sounds strange to me.

+4
source share
2 answers
public static void main(String[] args) {
    Runnable r = new Runnable() {
        @Override
        public void run() {
            System.out.println("hello world");
        }
    };
}

. , .

public class Foo {
    public void bar() {
        Runnable r = new Runnable() {
            @Override
            public void run() {
                System.out.println("hello world");
            }
        };
    }

    private void baz() {
    }
}

. , . run() baz() Foo.this.baz(), .

+8

, . , :

class Outer {
   void bar() {
      System.out.println("seems you called bar()");
   }

   void foo() {
     (new Runnable() {
       void run() {
         Outer.this.bar(); // this is valid
       }
     }).run();
   }

   static void sfoo() {
     (new Runnable() {
       void run() {
         Outer.this.bar(); // this is *not* valid
       }
     }).run();
   }
}

static , static .

+4

Source: https://habr.com/ru/post/1545476/


All Articles