Java

Inner Classes In Java

What is an inner class?

A class’s body contains definitions for its inner classes (known as outer class). These classes may be designated as final and abstract, or they may include access modifiers. Inner classes and instances of outer classes interact differently. They gain access to members of the upper and private classes thanks to this connection.

Inner classes can be defined in four different following ways as mentioned below:

1) Inner class
2) Method – local inner class
3) Anonymous inner class
4) Static nested class

1) Inner class

Within the curly braces of another enclosing class, an inner class is defined. As seen below, an inner class is coded within a top-level class:

//Top level class definition
class MyOuterClassDemo {
   private int myVar= 1;

   // inner class definition
   class MyInnerClassDemo {
      public void seeOuter () {
         System.out.println("Value of myVar is :" + myVar);
      }
    } // close inner class definition
} // close Top level class definition

Inner class may have any access modifiers, including abstract, final, public, protected, private, and static. They function as members of the surrounding class.
As seen in the example above, where the inner class is accessing the private variable “myVar” of the outer class, inner classes may access all members of the outer class, even those declared as private.

Instantiating an inner class
There must be a running instance of the outer class in order to instantiate an instance of the inner class. Only an instance of an outer class may be used to produce an inner class instance. An instance of the enclosing class and the inner class have a unique connection.
Creating an instance of an inner class from code in an outer class:

class MyOuterClassDemo {
   private int x= 1;
   public void innerInstance()
   {
       MyInnerClassDemo inner = new MyInnerClassDemo();
       inner. seeOuter();
   }
   public static void main(String args[]){
       MyOuterClassDemo obj = new MyOuterClassDemo();
       obj.innerInstance();
   }
   // inner class definition
   class MyInnerClassDemo {
       public void seeOuter () {
          System.out.println("Outer Value of x is :" + x);
       }
   } // close inner class definition	   
} // close Top level class definition

Output:

Outer Value of x is :1

Instantiating an inner class from outside the outer class Instance Code:

This code may be used in lieu of the public static void main in the preceding example. The output will likewise be the same.

public static void main(String args[]){
   MyOuterClassDemo.MyInnerClassDemo inner = new MyOuterClassDemo().new MyInnerClassDemo();
   inner. seeOuter();
}

2) Method–Local inner classes

A method of the enclosing class contains the definition of a method local inner class. Inner classes must be instantiated in the same procedure as the class declaration code if you wish to utilize them. For method-local inner classes, there are only two modifiers that are permitted: final and abstract. The inner class may only access the method’s local variables (where it is present) if they are designated as final.

//Top level class definition
class MyOuterClassDemo {
   private int x= 1;

   public void doThings(){
      String name ="local variable";
      // inner class defined inside a method of outer class
      class MyInnerClassDemo {
        public void seeOuter () {
           System.out.println("Outer Value of x is :" + x);
           System.out.println("Value of name is :" + name);//compilation error!!
        } //close inner class method
      } // close inner class definition
   } //close Top level class method
} // close Top level class

The aforementioned code will fail to compile because the inner class is unable to access the method’s non-final variables.
How to repair it is as follows: Inner classes may utilize a variable that has been marked as final.

final String name ="local variable";// inner object can use it

3) Anonymous Inner Classes

It is a specific kind of inner class that

  • Lacks a name
  • Can only be instantiated once.
  • Is often defined inside of a method or code block, in a set of curly braces with a semicolon at the conclusion.
  • Is only reachable from the point at which it is defined.
  • Is missing a constructor merely because it lacks a name.
  • No one can be static.
    Example:
package beginnersbook.com;
class Pizza{
   public void eat()
   {
      System.out.println("pizza");
   }
}
class Food {
   /* There is no semicolon(;)  
    * semicolon is present at the curly braces of the method end.
    */
   Pizza p = new Pizza(){
      public void eat()
      {
         System.out.println("anonymous pizza");
      }
   };
}

4) Static Nested Classes

A static nested class is an inner class that has the static modifier appended to it. Because this sort of inner class is static in nature, it has no particular connection with an instance of the outer class and is unable to access the outer class’s non-static members.

Example:

class Outer{
   static class Nested{}
}

static nested class can be instantiated like this:

class Outer{// outer class
   static class Nested{}// static nested class
}

class Demo{
   public static void main(string[] args){
      // use both class names
      Outer.Nested n= new Outer.Nested();
   }
}

Reference(s)

Java 2 by Bert Bates and Kathy Sierra

Related Articles

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button