简体   繁体   中英

Java: nested method local inner classes and accessibility

I've been trying out various scoping tricks using nested classes and found one particular case I'm stumped on.

Assume you have doubly nested local classes as so:

public class Outer {
    private final String className = "outer";

    public Outer() {}

    public void doThings() {
        class Inner {
            private final String className = "inner";
            public Inner() {}
            public void doThings() {
                class InnerInner {
                    private final String className = "inner-inner";
                    public InnerInner() {}
                    public void doThings() {
                        System.out.println("Outer class: "+Outer.this.className);
                        // How to access the Inner member?
                        System.out.println("InnerInner class: "+this.className);
                    }
                }

                InnerInner ii = new InnerInner();
                ii.doThings();
            }
        }

        Inner i = new Inner();
        i.doThings();
    }

    public static void main(String args[]) {
        Outer o = new Outer();
        o.doThings();
    }
}

As near as I can tell, class Inner is out of scope of the InnerInner class. Is there anyway that InnerInner can see its calling instance of Inner? Of course, using Outer.Inner.this.className would fail because Inner is not visible through Outer.

As an aside, I do realize this is a highly unconventional and improper java idiom but one that I believe is interesting especially to highlight the difference between scope chaining in prototypal languages like javascript and OO languages like java.

试试以下-

System.out.println("Inner class: " + Inner.this.className);

你可以这样尝试

 System.out.println("Inner class: " + Inner.this.className);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM