In addition to defining methods and fields within a class, it is also possible to define a class within a class. Such classes are nested classes. You use a nested class when the class makes little sense outside the context of its containing class. Consider a class that handles the command-line options of a program. Such a class is generally unique to each program and there is no reason to make a CommandLine class accessible from outside the class that contains Main(). Listing 5.39 demonstrates such a nested class. Listing 5.39. Defining a Nested Class
The nested class in this example is Program.CommandLine. As with all class members, no containing class identifier is needed from inside the containing class, so you can simply refer to it as CommandLine. One unique characteristic of nested classes is the ability to specify private as an access modifier for the class itself. Because the purpose of this class is to parse the command line and place each argument into a separate field, Program.CommandLine is relevant only to the Program class in this application. The use of the private access modifier defines the intended scope of the class and prevents access from outside the class. You can do this only if the class is nested. The this member within a nested class refers to an instance of the nested class, not the containing class. One way for a nested class to access an instance of the containing class is if the containing class instance is explicitly passed, such as via a constructor or method parameter. Another interesting characteristic of nested classes is that they can access any member on the containing class, including private members. The converse to accessing private members is not true, however. It is not possible for the containing class to access a private member on the nested class. Nested classes generally occur rarely.
|