简体   繁体   English

为什么我不能在声明方法之外访问本地类?

[英]Why can't I access local class outside declaring method?

I recently bumped into a rare -- but perfectly legal syntax: Local Classes . 最近,我碰到了一种罕见但合法的语法: Local Classes

I was wondering why can't I access a local class outside that method? 我想知道为什么我不能在该方法之外访问本地类? With what is it different from an inner class which can be access in the outer class or with an enclosed object ( outer.new Inner() )? 它与可以在外部类中访问或使用封闭对象( outer.new Inner() )的内部类有什么不同?

Example: this is perfectly valid, 例子:这是完全正确的,

//this is valid
public class Outer {
    int outer_x = 100;

    public void test() {
        Inner inner = new Inner();
        inner.display();

    }

    public class Inner {
        public void display() {
            System.out.println("Outer x is: " + outer_x);
        }
    }
}

This is valid as well 这也是有效的

 //this is valid as well
public class Outer {
    int outer_x = 100;

    public void test() {
        Inner inner = new Inner();
        inner.display();
    }

    public class Inner {
        public void display() {
            System.out.println("Outer x is: " + outer_x);
        }
    }

    public void test2() {

        Inner inner2 = new Inner();
        inner2.display();
    }
}

But this will not compile: 但这不会编译:

public class Outer {
    int outer_x = 100;

    public void test() {

        class Inner {

            public void display() {
                System.out.println("Outer x is: " + outer_x);
            }
        }
        Inner inner = new Inner();
        inner.display();

    }

    public void test2() {

        Inner inner2 = new Inner(); // error here
        inner2.display();
    }
}

Why is this so? 为什么会这样呢?

Because every call to test() creates a complete new version of the class. 因为每次调用test()都会创建该类的完整新版本。 Therefore it may access (final or effectively final) local variables! 因此,它可以访问(最终或有效地最终)局部变量!

Here's a rundown what's going on. 这是一个失败的过程。

public class Outer {

    public void test(int i) {
        class Inner {
            private int x = i; // i may be different on each call of test

            public void display() {
                System.out.println("Inner x is: " + x);
            }
        }
        Inner inner = new Inner();
        inner.display();
    }

    public void test2() {
        test(1); // prints 1
        test(2); // prints 2

        //now imagine this is valid
        Inner inner2 = new Inner();
        inner2.display();// what's the value of x??
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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