【问题标题】:compile fail when changing inner class to static将内部类更改为静态时编译失败
【发布时间】:2015-05-07 13:12:23
【问题描述】:

关于将非静态内部类更改为静态为什么运行代码时出现编译时错误说-

非法封闭实例规范

public class TestingInnerStatic{  
   public static void main(String args[]) {
       InnerSame innerSame       = new TestingInnerStatic().new InnerSame();//compile fail
       Outer.InnerDiff innerDiff = new Outer().new InnerDiff();//compile fail
       } 
   public void main() {
       InnerSame innerSame       = new InnerSame();
       Outer.InnerDiff innerDiff = new Outer().new InnerDiff();//compile fail
   }
   static class InnerSame{}

}

class Outer{
    static class InnerDiff{}
}

以其他成员为例,这只是在类的引用上调用静态成员的约定和良好做法,但是如果您在对象上调用它们,它们不会显示编译失败。那么为什么会出现编译失败?

【问题讨论】:

  • 新 Boxing1().new InnerSame();尝试更改为 new Boxing1.InnerSame();其他失败也一样..
  • 为什么这在对象上不可用?
  • 类 Outer 在它自己的文件中吗?
  • 我认为new Boxing1().new InnerSame(); 应该是new TestingInnerStatic().new InnerSame();
  • @Pratik this is only 重载。

标签: java static inner-classes


【解决方案1】:

如果内部类是非静态的,那么您需要外部类的实例来创建内部类的实例。但静态类的情况并非如此,内部静态类的实例可以在没有外部类的实例的情况下存在。

静态示例:

InnerClass ic = new Outer.InnerClass();

请注意,我没有创建外部类的新实例。

编辑:reference

【讨论】:

  • 所以这是仅通过引用外部类来创建内部对象的附加访问权限。为什么它不适用于外部类对象?
  • 以其他成员为例,这只是在类的引用上调用静态成员的约定和良好做法,但如果你在对象上调用它们,它们不会显示编译失败。那么为什么会有是编译失败吗?
  • 不要将静态内部类视为属于外部类的实例。虽然您可以从该类的实例访问静态方法和变量(如果您这样做,IDE 会抱怨这一点),但静态内部类并非如此。从我提供的参考链接Note: A static nested class interacts with the instance members of its outer class (and other classes) just like any other top-level class. In effect, a static nested class is behaviorally a top-level class that has been nested in another top-level class for packaging convenience.
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-04-07
  • 2012-07-03
  • 2012-05-01
  • 1970-01-01
  • 2013-05-12
相关资源
最近更新 更多