Difference between static nested class and regular class

前端 未结 5 1136
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-11 07:52

I know this is a bit of a duplicate question but I want to ask it in a very specific way in order to clarify a very important point. The primary question being: Is there any

5条回答
  •  盖世英雄少女心
    2020-12-11 08:29

    There are several subtle differences.

    Probably the most important one is that a nested static class can be made private or protected. A top-level class can only be package-private or public.

    The other differences I can think of are technical details, which you probably should not write code where those details matter:

    • A nested static class can "hide" or "shadow" other classes of the same name. When a nested static class has the same name as an outer class, and both are in scope, the nested static class hides the outer class.

    • A nested static class is inherited by subclasses of its outer class, so it is in scope in those subclasses and can be referred to without a fully-qualified name or a static import.

    • Two outer-level classes in the same package cannot share the same name, but a class can inherit multiple nested static classes of the same name (e.g. from two interfaces). This does not result in a compilation error unless the nested class's name is used ambiguously.

    • A nested static class can have multiple different fully-qualified names due to inheritance, for example in class A { static class B extends A {} } the class A.B can be referred to as A.B.B, A.B.B.B, and so on. An outer class can only have one fully-qualified name.

    • An outer class's canonical name equals its binary name, but a nested static class's canonical name is not equal to its binary name. The binary name of a nested static class has the symbol $ separating the outer class's binary name from the nested static class's simple name.

提交回复
热议问题