Why a non-static inner-class cannot have static members (fields and methods)? [duplicate]

丶灬走出姿态 提交于 2019-11-28 10:07:26

Technically there I don't know of any reason why the language restricts the use of static elements for inner classes. A nonstatic inner class can be emulated by using a normal class that takes the (formerly) enclosing instance as an argument to the constructor. Of course there are many little differences when it comes to visibility rules an visibility scopes.

I presume it was a language design decision, mostly because statics in non-static inner classes are confusing and non-intuitive to access (Outer.Inner.StaticMember).

1. An object of a Non-static inner class is associated with an instance/object of its Outer Class (ie enclosing class).

2. The entire body of a Non-static inner class is Not within a static scope, and therefore you can't have static members in there.

3. Instance variables and methods in the non-static inner class are relative to an instance of the enclosing class, so being related to an object, static won't hold true for them (ie inner class),

4. When we create an Instance of non-static inner class, we Need an Object of Outer enclosing class. The innernon-static class has an implicit reference to it outer enclosing class.

Eg:

Outer o = new Outer();
Outer.Inner i = o.new Inner();

There is no point of providing a static method inside a non static inner class. You could use a non static method inside the outer class instead ?

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