Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inner class and local variables

Why do I need to declare a local variable as final if my Inner class defined within the method needs to use it ?

Example :

class MyOuter2 {

private String x = "Outer2";

void doStuff() {
    final String y = "Hello World";

    final class MyInner {

        String z = y;

        public void seeOuter() {
            System.out.println("Outer x is "+x);
            System.out.println("Local variable is "+y);
            MyInner mi = new MyInner();
            mi.seeOuter();
        }
    }
}

}

Why the String y needs to be a final constant ? How does it impact ?

like image 254
AllTooSir Avatar asked Apr 26 '12 17:04

AllTooSir


People also ask

What is the difference between inner class and local class?

inner class: Can only exist withing the instance of its enclosing class. Has access to all members. local class: class declared in a block. It is like an inner class (has access to all members) but it also has access to local scope.

What is local inner class?

Local Inner Classes are the inner classes that are defined inside a block. Generally, this block is a method body. Sometimes this block can be a for loop or an if clause. Local Inner classes are not a member of any enclosing classes.

Can an inner class declared inside of a method access local variables of this method?

Yes, we can access the local final variables using the method local inner class because the final variables are stored on the heap and live as long as the method local inner class object may live.

What is local inner class in Java with example?

Method-local Inner Class In Java, we can write a class within a method and this will be a local type. Like local variables, the scope of the inner class is restricted within the method. A method-local inner class can be instantiated only within the method where the inner class is defined.


1 Answers

Local variables always live on the stack, the moment method is over all local variables are gone.

But your inner class objects might be on heap even after the method is over (Say an instance variable holds on to the reference), so in that case it cannot access your local variables since they are gone, unless you mark them as final

like image 154
mprabhat Avatar answered Sep 26 '22 12:09

mprabhat