java - 创建局部内部类的实例

标签 java inner-classes

案例一

 class Outer {    

    void outerMethod() {
        Inner i = new Inner();    //compile error : cannot find symbol
        i.innerMethod();

        class Inner {
            void innerMethod() {
                System.out.println("inner class method...");
            }
        }       
    }
}


案例二

class Outer {    

    void outerMethod() {
        Inner i = new Inner();
        i.innerMethod();        
    }
    class Inner {
            void innerMethod() {
                System.out.println("inner class method...");
            }
    }   
}

这两种情况下有两个独立的类文件。但一个出现编译错误,另一个正常。这是什么原因?

最佳答案

Local classes有不同的范围规则。 来自JLS, section 6.3 :

"The scope of a local class declaration immediately enclosed by a block (§14.2) is the rest of the immediately enclosing block, including its own class declaration. "

在你的第一个例子中,你在这个内部类的范围之前调用了内部类的构造函数,因此这是非法的。

在您的代码中说明这一点:

void outerMethod() {
    // ...        
    // ...

    // Beginning of legal usage scope of the local class
    class Inner {
        void innerMethod() {
            System.out.println("inner class method...");
        }
    }
    // ...
    // ...
    // End of legal usage scope of the local class
}

关于java - 创建局部内部类的实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22931447/

相关文章:

java - 错误 :Internal error: (java. lang.NoSuchMethodError)影响我所有的项目

java - 从封闭的成员类访问阴影字段 (Java)

c++ - 将 C 识别的指针类型定义为内部 C++ 类

java - Apache POI : find characters in Word document without spaces

在 Couchbase 中更新插入文档的 Java 线程无限期地陷入等待状态

java - 两个类来扩展一项 Activity ?

java - 在 Eclipse 中跳转到 block 的开头/结尾

java - 访问内部类内的变量

c++ - 如何将模板类的内部类分离到其他文件中

android - 如何运行使用内部类的线程?