When is really useful to use a nested Java class?

后端 未结 4 990
猫巷女王i
猫巷女王i 2021-01-25 03:52

Could you give me a concrete example where a nested java class is useful? I am studying it, I understand how it works but I can not imagine a real situation where its use is rea

4条回答
  •  遥遥无期
    2021-01-25 04:21

    Nested classes are a way to organizing your code, one could say, sort of tight Encapsulation. While nested classes are not applicable to all situations, they are particularly useful when handling events.

    The scope of a nested class is bounded by the scope of its enclosing class. So, if class B is defined within class A, then B does not exist independently of A. A nested class has access. to the members, including private members, of the class in which it is nested. However, the enclosing class does not have access to the members of the nested class. A nested class that is declared directly within its enclosing class scope is a member of its enclosing class.

    The most used is the inner class. An inner class is a non-static nested class. It has access to all of the variables and methods of its outer class and may refer to them directly in the same way that other non-static members of the outer class do.

    Finally there are anonymous inner classes, which are inner classes that don’t have a name.

提交回复
热议问题