Member Classes, Inner Nested Classes in java

This page discusses - Member Classes, Inner Nested Classes in java

Member Classes


 Member classes are defined within the body of a class. We can use member classes anywhere within the body of the containing class. We declare member classes when we want to use variables and methods of the containing class without explicit delegation.
The member class is the only class that we can declare static. When we declare a member class, we can instantiate that member class only within the context of an object of the outer class in which this member class is declared. If we want to remove this restriction, we declare the member class a static class.

Local classes

Local classes are same as local variables, in the sense that they're created and used inside a code block (i.e., a function, a static initializer, or a code block within a function or static initializer). Once you declare a class within a block, it can be instantiated as many times as you wish within that block. A local class has all the features of a member class, but like local variables, local classes are not allowed to be declared public, protected, private, or static. The name of the class can only be used within the function, if the local class fall down from some other class or interface whose name is generally visible.

Anonymous Classes

Anonymous classes are declared and instantiated within the same statement. We can say that it is a local class that is defined without a class name, the anonymous classes  are instantiated only once. Simply we can say that we should create a new class every time when we execute a given anonymous class definition. It is very convenient to define a class right in the middle of an expression which is allows us by an inner class

The syntax of anonymous classes is as under :

new class-name ( [ argument-list ] ) { class-body }

Because an anonymous class doesn't have a normal class declaration where it's possible to use static , it cannot be declared static.

We use the anonymous class when the class has a very short body as well as when there is only one need of the instance of the class is needed and the name of the class does not make our code easy to understand.