Why outer classes are not static in java? [duplica

2020-03-30 16:21发布

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

public static class MyClass{}

1条回答
聊天终结者
2楼-- · 2020-03-30 16:40

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();
    }
  }

}
查看更多
登录 后发表回答