Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent anonymous class from referencing outer members in Java

Tags:

java

In Java, is there a way to explicitly prevent an anonymous class to reference the outer class or method's members/local variables?

like image 671
Pinch Avatar asked Apr 28 '26 20:04

Pinch


1 Answers

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.

like image 178
MC Emperor Avatar answered Apr 30 '26 10:04

MC Emperor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!