Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are captured variables in Java Local Classes

Tags:

java

The Java documentation for Local Classes says that:

In addition, a local class has access to local variables. However, a local class can only access local variables that are declared final. When a local class accesses a local variable or parameter of the enclosing block, it captures that variable or parameter. For example, the PhoneNumber constructor can access the local variable numberLength because it is declared final; numberLength is a captured variable.

What is captured variable,what is its use and why is that needed? Please help me in understanding the concept of it.

like image 830
Chaitanya Avatar asked Feb 25 '14 20:02

Chaitanya


People also ask

What is variable capture in Java?

Variable capture is when the local variables within the local function in which the nested class is defined in, is being captured inside of the instance of the inner class in the heap.

What are local variables in Java?

A local variable in Java is a variable that's declared within the body of a method. Then you can use the variable only within that method. Other methods in the class aren't even aware that the variable exists. If we are declaring a local variable then we should initialize it within the block before using it.

What is local variable in class?

Local variables − Local variables are declared in methods, constructors, or blocks. Local variables are created when the method, constructor or block is entered and the variable will be destroyed once it exits the method, constructor, or block.


1 Answers

What is captured variable,what is its use and why is that needed?

A captured variable is one that has been copied so it can be used in a nested class. The reason it has to be copied is the object may out live the current context. It has to be final (or effectively final in Java 8) so there is no confusion about whether changes to the variable will be seen (because they won't)

Note: Groovy does have this rule and a change to the local variable can mean a change to the value in the enclosing class which is especially confusing if multiple threads are involved.

An example of capture variable.

public void writeToDataBase(final Object toWrite) {
    executor.submit(new Runnable() {
        public void run() {
             writeToDBNow(toWrite);
        }
    });
    // if toWrite were mutable and you changed it now, what would happen !?
}
// after the method returns toWrite no longer exists for the this thread...
like image 123
Peter Lawrey Avatar answered Oct 21 '22 06:10

Peter Lawrey