【问题标题】:What is the difference between static class and not static class inside Interfaces? [duplicate]接口内部的静态类和非静态类有什么区别? [复制]
【发布时间】:2016-08-20 21:11:50
【问题描述】:

在下面的代码中,我们可以证明接口内部可以声明静态类和非静态类(静态嵌套类和内部类)。好的,没有新的。但是,如果“内部”类可以有一个没有外部类实例的实例,“嵌套”类和“内部”类(内部接口)有什么区别,即使在接口实现(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{

}

【问题讨论】:

  • 接口中的类??常见.. AFAIK、publicstatic 修饰符在界面中是多余的
  • 您好,我不确定我是否正确理解了您的问题,如果没有请告诉我。使用静态方法的一般约定不需要 new 关键字,它是为创建实例而设计的。所以我们可以期待 MyClass.MyInner();工作,但它也不会编译,因为 MyInner 不是静态的,然后它应该只在实例范围内可用,然后它将再次使用: new MyClass().MyInner();另一方面 new MyInterf.MyNested() 将起作用,因为接口将事物声明为隐式静态。 (正如 Thufir 所说)希望有所帮助

标签: java interface static nested


【解决方案1】:

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

编辑感谢Andreascomment 中指出MyInterf.MyInner 是一个静态嵌套类,而不是一个内部类 em>。

来源:Java spec, sec. 9.5

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

【讨论】:

  • 你为什么不投票接近重复?
  • “接口内的内部类实际上是隐式静态的” 用语自相矛盾。 内部类被定义为一个非静态嵌套类。成为static 意味着它不能是一个内部类,而是一个嵌套类;更具体地说是一个静态嵌套类。请参阅JLS 8.1.3 - Inner Classes and Enclosing Instances内部类是一个嵌套类,显式或隐式声明static
  • @Andreas 已更新 - 谢谢!
  • @RC。因为 (1) Thufir 已经知道链接问题的答案 :) 和 (2) Nad Nik 的答案,在我看来是最相关的,在页面下方很远,我不想让 Thufir 去寻找答案。如果对链接问题的接受答案也在这里回答了这个问题,我可能会投票重复。但是,我从来没有竞选过主持人,所以... ;)
猜你喜欢
  • 1970-01-01
  • 2013-07-05
  • 2012-05-26
  • 2011-07-11
  • 1970-01-01
  • 2013-07-26
  • 2013-07-21
  • 2014-10-31
  • 2016-10-21
相关资源
最近更新 更多