3) Inner Classes

A nested class is a class defined within another class. Nested classes that are declared as static are referred to as static nested classes. Nested classes that aren’t declared as static are referred to as inner classes. Like a regular top-level class, an inner or static nested class can define variables and methods.

Create top-level and nested classes :

Advantages of inner classes :

  1. Objectify the functionality of a class, within it.For example, you might define a class Tree, which defines operations to add objects, remove objects, and sort them based on a condition. Instead of defining methods and variables to sort them within the class Tree, you could encapsulate sorting functionality within another class TreeSort. Because the class TreeSort would always work with Tree and might not be needed outside the class Tree, TreeSort can be defined as an inner class within class Tree.

  2. For using inner classes is as parameter containers.Instead of using long method signa- tures, inner classes are often used to keep method signatures compact by passing ref- erence parameters of inner classes instead of a long list of individual parameters.

Last updated