Java Inner Class

09:31:00

Java Inner Class step by step tutorial

Java Inner Class

Java inner class or nested class is a class
Eg. declared inside the class or interface.
We use inner classes to logically group classes and interfaces in one place so that it can be more readable and maintainable.
Additionally, it can access all the members of outer class including private data members and methods.

 

Syntax of Inner class

1.      
2.     class Java_Outer_class{  
3.      //code  
4.      class Java_Inner_class{  
5.       //code  
6.      }  
7.    


Advantage of java inner classes

There are basically three advantages of inner classes in java. They are as follows:
1) Nested classes represent a special type of relationship that is it can access all the members (data members and methods) of outer class including private.
2) Nested classes are used to develop 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.

Difference between nested class and inner class in Java

Inner class is a part of nested class. Non-static nested classes are known as inner classes.

Types of Nested classes

There are two types of nested classes non-static and static nested classes.The non-static nested classes are also known as inner classes.
1.     Non-static nested class(inner class)
o    a)Member inner class
o    b)Anonymous inner class
o    c)Local inner class
2.     Static nested class

Java Local inner class

A class i.e. 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.

Java local inner class example


1.      
2.     public class localInner1{  
3.      private int data=30;//instance variable  
4.      void display(){  
5.       class Local{  
6.        void msg(){System.out.println(data);}  
7.       }  
8.       Local l=new Local();  
9.       l.msg();  
10.                         }  
11.                         public static void main(String args[]){  
12.                          localInner1 obj=new localInner1();  
13.                          obj.display();  
14.                         }  
15.                        }  

Output:
30



You Might Also Like

0 comments

Thanks for intrest.. We will touch withbyou soon..

Popular Posts

Like us on Facebook