Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous classes enclosing instances

Tags:

java

I'm reading Joshua Blochs "Effective Java" 2nd edition. Currently I'm at item 22 which describes inner and nested classes but I can't understand what does he mean by this sentence:

Anonymous classes have enclosing instances if and only if they occur in a nonstatic context.

Can someone give me an example of code and explain what does it exactly do ? I know that if InnerClass is a member of OuterClass its enclosing instance is OuterClass, but in terms of annonymous class it sounds strange to me.

like image 860
ashur Avatar asked Dec 12 '22 05:12

ashur


2 Answers

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

Here, an anonymous class instance is created from a static context. So it doesn't have any enclosing instance.

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

    private void baz() {
    }
}

Here, an anonymous class instance is created from an instance method. So it has an enclosing instance. The run() method could call baz() or Foo.this.baz(), thus accessing a method from this enclosing instance.

like image 163
JB Nizet Avatar answered Dec 21 '22 12:12

JB Nizet


The effect is the same as for non-anonymous inner classes. In essence, it means:

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

Because you cannot give the static modifier to anonymous classes, the static property is always inherited from the context.

like image 31
Waldheinz Avatar answered Dec 21 '22 14:12

Waldheinz