Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
291 views
in Technique[技术] by (71.8m points)

java - 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...