![]() ![]() ![]() It can lead to more readable and maintainable code: Nesting small classes within top-level classes places the code closer to where it is used.Īs with instance methods and variables, an inner class is associated with an instance of its enclosing class and has direct access to that object's methods and fields. In addition, B itself can be hidden from the outside world. By hiding class B within class A, A's members can be declared private and B can access them. It increases encapsulation: Consider two top-level classes, A and B, where B needs access to members of A that would otherwise be declared private. Nesting such "helper classes" makes their package more streamlined. It is a way of logically grouping classes that are only used in one place: If a class is useful to only one other class, then it is logical to embed it in that class and keep the two together. (Recall that outer classes can only be declared public or package private.) Why Use Nested Classes?Ĭompelling reasons for using nested classes include the following: As a member of the OuterClass, a nested class can be declared private, public, protected, or package private. Static nested classes do not have access to other members of the enclosing class. Non-static nested classes (inner classes) have access to other members of the enclosing class, even if they are declared private. A nested class is a member of its enclosing class. ![]()
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |