What are inner classes and types of inner classes?
Answered
What are inner classes and types of inner classes?
Best answer
Java allows to define a class inside another class much like a variable and a method. This is called as Nested class.
class OuterClass { ... Â class NestedClass { Â ... Â } }
Nested classes help in logical grouping of classes that are only used in one place, they provide increased encapsulation. This will help to write a more readable and maintainable code. Nested classes could be of one of the four types:
-
- Static Nested Classes – Are static members of a class like static variables and methods. And like static class methods, a static nested class cannot refer directly to instance variables or methods defined in its enclosing class: it can use them only through an object reference.
-
- Inner Classes – Are classes defined as members of a class. An inner class is associated with an instance of its enclosing class and has direct access to that object’s methods and fields. Also, because an inner class is associated with an instance, it cannot define any static members itself.
-
- Local Classes – Are classes declared within a block of code and are visible only within that block, just as any other method variable.
-
- Anonymous Classes – Are local classes without a name. Anonymous classes enable you to make your code more concise. They enable you to declare and instantiate a class at the same time. Typically used when there is a need to use the class only once.