Sunday, 22 November 2015

Use Non-final variable inside Anonymous Inner Class

Accessing local variable inside an inner class need to be declared as final or effectively final(this is new in Java 8). 

But if we have a requirement of changing that variable after inner class then we can't declare the local variable as final. So to use that non-final local variable effectively inside inner class we can pass that variable as constructor argument to that inner class and use it.

Example : 

class IdGenerator {
    long id = 99990000;

    public IdGenerator() {
    }

    public String generateId() {
        return String.valueOf(++id);
    }
}

interface Service {
    void logData();
}
public class InnerClassWithNonFinalVariable {
    public static void main(String[] args) {
        IdGenerator idGenerator = new IdGenerator();

        class MyService implements Service {
            private IdGenerator generator;

            MyService(IdGenerator generator) {
                this.generator = generator;
            }

            @Override            public void logData() {
                System.out.println("Logging Data :" + this.generator.generateId());
            }
        }

        Service service = new MyService(idGenerator);
        service.logData();

        /* Using idGenerator for some other purpose */        idGenerator = null;
    }
}

But while working with Anonymous Inner Class, We don't have option to define constructor. So below demonstrated code shows how to use non-final local variable inside anonymous inner class.



No comments:

Post a Comment