group-icon
Java Developers
Group for Java developers and programmers. Ask questions and get answers related to Java programming
255 Members
Join this group to post and comment.
Gaurav Prasad
Gaurav Prasad
Computer Science
19 Jan 2019

What is inner class in java?

give one example stating it?

AdhikariHarika Reshma
AdhikariHarika Reshma
Computer Science
2mos ago

Inner classes are security mechanism in java.These are Non static nested class.It means it is  the class which is a member of another class.Also we can say that it is a part of nested class.It is used to logically group interfaces and classes in one place so that it can be more readable and maintainable.We know that class cannot be associated with access modifier private,but if we have the class as a member of another class then it can be made private.And it is also used to access the private members of the class.

The inner classes are of three types depending on how and where we define them.They are:

1.Inner class-Creating an inner class is quite simple.we need to write a class within another class.unlike a class,an inner class should be private and once we declare an inner class it cannot be accessed from an object outside the class.

class Out  //outer class
{
  
  private class Inn  //inner class
  {
   public void print()
   {
      System.out.println("This is a inner class");
   }
  }
   //Accessing the inner class from the method
   void display_Inner()
    { 
       Inn i=new Inn();
      i.print();
    }
}
public class My_class
{
  public static void main(String args[])
  { 
    //instantiating the outer class
    Out o=new Out();
    //accessing the display_Inner method
    out.display_Inner();
  }
}

2.Method Local Inner class-We can write a class within a method and it will be a local type.similar to local variables,the scope of the inner class is restricted within the method.

3.Anonymous Inner class-An inner class declared without a class name is known as Anonymous Inner class.In this case we declare and instantiate the class at the same time.