Java Inner Classes

Java inner class or nested class is a class which is 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
snippet
class Java_Outer_class{
 //code
 class Java_Inner_class{
  //code
 }
}

Advantage of 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.

  • What is the internal code generated by the compiler for member inner class ?
  • What are the two ways to create annonymous inner class ?
  • Can we access the non-final local variable inside the local inner class ?
  • How to access the static nested class ?
  • Can we define an interface within the class ?
  • Can we define a class within the interface ?

Difference between nested class and inner class

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.

  • Non-static nested class (inner class)
    1. Member inner class
    2. Anonymous inner class
    3. Local inner class
  • Static nested class
TypeDescription
Member Inner ClassA class created within class and outside method.
Anonymous Inner ClassA class created for implementing interface or extending class. Its name is decided by the java compiler.
Local Inner ClassA class created within method.
Static Nested ClassA static class created within class.
Nested InterfaceAn interface created within class or interface.
Related Tutorial
Follow Us
https://www.facebook.com/Rookie-Nerd-638990322793530 https://twitter.com/RookieNerdTutor https://plus.google.com/b/117136517396468545840 #
Contents +