接口内的静态类和非静态类有什么区别?

时间:2016-04-26 20:29:00

标签: java interface static nested

在下面的代码中,我们可以证明接口可以在内部声明静态类和非静态类(静态嵌套类和内部类)。好的,没有新的。但是,如果“内部”类可以有一个没有外部类实例的实例,即使在接口实现( MyInterfImpl >在下面的代码中)?

我已经对代码中的行进行了评论,以“突出显示”:

public class NewTest {

    public static void main(String[] args) {

        // OK Compilation Fail on next line, here we can't have an Instance of inner class because we don't have
        // instance of outer class, nothing strange to me
        MyClass.MyInner inner = new MyClass.MyInner(); //COMPILE FAIL:  must be new MyClass().new MyInner() instead
        MyClass.MyNested nested = new MyClass.MyNested(); // OK here, its nested

        MyInterf.MyInner inner2 = new MyInterf.MyInner(); // HERE, MyInner is Inner class, ins't it? 
        MyInterf.MyNested nested2 = new MyInterf.MyNested(); // OK here, its nested

        MyInterfImpl.MyInner inner3 = new MyInterfImpl.MyInner(); // // HERE, MyInner is Inner class, ins't it? 
        MyInterfImpl.MyNested nested3 = new MyInterfImpl.MyNested(); // // OK here, its nested

    }




}

interface MyInterf{

    public static class MyNested{

    } // end

    public class MyInner{

    }//

    // some abstract methods....
}

class MyClass{
    public static class MyNested{

    } // end

    public class MyInner{

    }// end
}

class MyInterfImpl implements MyInterf{

}

1 个答案:

答案 0 :(得分:1)

this answerNad Nik:接口内的类实际上隐含了staticpublic。所以MyInterf.MyInner()工作正常,因为MyInterf.MyInner实际上是静态的。

修改感谢Andreascomment中指出MyInterf.MyInner静态嵌套类,而不是< em>内部课程。

来源:Java spec, sec. 9.5

朋友,我希望你不要背对着任何门。 :)