Witscale Test Center

4.2 Why inner classes > 4.2.3 The organizational reasons


4.2.3 The organizational reasons

Some classes like the event-listeners in the above example are useful only within a particular class. Such classes are not very useful if visible to the other classes in the same package. In that case, defining them as top-level class may only clutter the package. For example, assume that MailClient is defined in com.example.communication package and it uses two event-listener classes, InboxHandler and ComposeMailHandler. If you define these two classes as top-level classes, they will be (unnecessarily) accessible to all other classes within the same package as MailClient. On the other hand, if you declare them as inner classes, they will be compiled to MailClient$InboxHandler.class and MailClient$ComposeMailHandler.class. Now there won’t be a separate top-level class for each event-listener. Thus the package still has three class files (MailClient.class, MailClient$InboxHandler.class and MailClient$ComposeMailHandler.class), but the com.example.communication namespace is really using only MailClient class name. The package namespace is not cluttered with the names of event-listeners. Thus, the inner classes help in better organization of classes. Instead of putting everything in package, classes (that provide some class-specific functionality) can be further organized within a class.