Java Tut – Nested or Inner Class

Syntax:

1) Nested classes represents a special type of relationship that it can access all the members(data members and methods) of outer class including private
2) Nested classes are used to deelop more readable and maintainable code because it logically group classes and interfaces in one place only.
3)Code optimization:It requires less code to write.

Types of Nested classes:
1. Non-static nested class(inner class)
a) Member inner class
b) Anonymouse inner class
c)Local inner class
2. Static nested class

Non static nested class is known as inner class

Java member inner class:

example:

Java Anonymous Inner Class
A class that have no name is known as anonymous inner class in java.It should be used if you have to override method of class or interface. Java anonymou inner class can be created by two ways:
1.Class(may be abstract or concrete)
2. Interface

Java anonymlus inner class example using class

Internal working of given code:

1. A class is created but its name is decided by the compiler which extends the Person class and provides the implementation of the eat() method.
2. An object of anonymous class is created that is referred by p reference variable of Person type.

Internal class generated by the compiler:

Local inner class:
A class created inside a method is called local inner class in java.If you want to invoke the methods of local inner class, you must instantiate this class inside the method.
example:

Static nested class example with instance method:

Java Nested Interface:
syntax of nested interface which is declared within the interface

Syntax of nested interface which is declared within the class