In Java, is there a way to explicitly prevent an anonymous class to reference the outer class or method's members/local variables?
There isn't. You always define anonymous classes inside other classes, e.g.
class A {
private String aMember;
public void test() {
B b = new B() {
@Override
public void b() {
...
}
};
}
}
You can always use OuterClassName.this.something to access the outer class:
@Override
public void b() {
A.this.aMember = "Hello";
}
Why do you want to restrict access to the outer class? Once we know that, we could better understand what you're trying to achieve.
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