Describe and develop code that uses Java inner classes, including nested class, static class, local class, and anonymous classes
What is a nested class?
The Java programming language allows you to define a class within another class. Such a class is called a nested class.
Why Use Nested Classes?
- 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. Nesting such “helper classes” makes their package more streamlined.
- 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. By hiding class B within class A, A’s members can be declared private and B can access them. In addition, B itself can be hidden from the outside world.
- 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.
Types of Inner classes
Based on the place of the class which we defined the interface and the modifier we use inner classes can be categories as follows.
Static Inner classes
As with class methods and variables, a static nested class is associated with its outer class. When working with static inner class we should treat them as the same way we treat other static members of a class. So
- Similar to inner class, but declared as static
- No link to an instance of the outer class.
- Can only access static fields and methods of the outer class.
To refer static nested class we can use the outer class name as follows;
For example, to create an object for the static nested class, we can use following syntax:
OuterClass.nestedClass example = new OuterClass.nestedClass( );
You can access OCPJP Upgrade 8 (1Z0-810) Exam full study notes at MyExamCloud’s OCPJP 8 Upgrade Study Plan .