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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With