Why outer classes are not static in java? [duplicate]

随声附和 提交于 2019-12-30 11:34:12

问题


In java, An outer class may be public, final, default or abstract. Why not Static like

public static class MyClass{}


回答1:


An outer class is already implicitly static.

Non-static nested class (= inner class) means thats the inner class implicitly has a reference to its parent class.

That's why, for nested class, you can distinguish between static and non-static. This does not make sense for outer classes.

Here is an example to understand the difference between static/non-static nested class. You should understand why it does not make sense in an outer class.

public class MyClass {

  private String anAttributeOfMyClass;

  private /*static*/ class MyInnerClass {

    public void foo() {
      /*
       * Here, I can access the attribute of the parent class
       * because I implicitly have a reference to it.
       * Try to make the nested class static an see the difference.
       */
      anAttributeOfMyClass.trim();
    }
  }

}


来源:https://stackoverflow.com/questions/18738049/why-outer-classes-are-not-static-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!