top of page
kisha2001prajapati

Java Inner Classes

Java inner class or nested class is a class that is declared inside the class or interface.


We use inner classes to logically group classes and interfaces in one place to be more readable and maintainable.


Additionally, it can access all the members of the outer class, including private data members and methods.


Types of inner classes:


  1. Static Inner Class

  2. Non-Static Inner Class

• Member Inner Class

• Local Inner Class

• Anonymous Inner Class


1. Static inner class


• A class which is declared by using static keyword and created inside a class, its called a static inner class.

• It can access only static data of outer class but cannot access any non static data.





2. Non-static inner class

  • Member Inner Class :

• A non static class which is declared inside of the class but outside of the method body, its called member inner class. It is also called regular inner class.

• We can create an object of the inner class with the help of object of outer class as it exist within the object of outer class.




  • Local Inner Class:

• A non static class which is declared inside of the method body of the outer class, its called local inner class.

• Local Inner classes does not have any access modifier associated with them as it belongs to the body method in which they are declared. However, they can have abstract and Final modifiers.

• We can create an object of local inner class inside the body method in which they are declared. Through which we can access its data.




  • Anonymous Inner Class:

• A non static class which does not have any name, it is called Anonymous Inner class. For which only single object is created.

• It is useful in method overloading.

• We cannot create an object of in interface, in such cases, we can use anonymous class to implement or overload the method.

• Anonymous class does not have any name so Java compiler will decide its name while compiling the code.




Advantages of using inner class


• It enhances the organization and readability of the code.

• It shows a special relationship, that is it can access all the data member of its outer class including private. So, it is useful when user wants to program in such a way that no other class can access the data, except inner class.

• In addition, it require less code to write.

• Inner classes are security mechanism in java.

17 views0 comments

Recent Posts

See All

Comments


bottom of page