Java Programming Tutorial Index

Miscellaneous

Java allows a programmer to write a class within another. Inner classes in Java are formed from nesting of one or more classes within another class. Like that of methods, variables of any class also have the possession of another class as its' component or member. The concept of the writing of classes within another is called nested classes. There are two components in a nested class; the class that clings to an inner class is the outer class.



Here's how nesting of the class is done and inner classes can e formed:

Syntax:

class Outer_class {
 // body of outer class
 class Inner_class {
  // body of inner class
 }
}

Types of Inner Class

Programmers can write inner classes in two different types. These are:

  • Local - Method Inner class
  • Anonymous Inner class

Local method Inner class

Java programmers have provision to create or define a class inside a method, and its type will be local. Like that of local variables, the inner class has a scope restricted within the curly braces of the method.

Example:

public class classA {
 void fun() {
  int val = 84;
  // local-method inner class
  class InnerMeth {
   public void disp() {
     System.out.println("Inner class method: "+val);       
     }
    } // end of inner class   
    // Accessing the inner class
   InnerMeth in = new InnerMeth(); in .disp();
  }

  public static void main(String argu[]) {
   classA out = new classA();
   out.fun();
   System.out.println("Program done….");

  }
 }

Output:

Inner class method: 84
Program done….

Anonymous Inner class

An inner class having no class name of its own is termed as an anonymous inner class. For anonymous inner classes, you have to state them, i.e.define and instantiate these classes at the same time. These type of anonymous classes comes handy where programmers need to override methods of a class or interface within a program.

Example:

abstract class anonInner {
 public abstract void fun();
}

public class outerA {
 public static void main(String argu[]) {
  anonInner in = new anonInner() {
   public void fun() {
    System.out.println("Anonymous Inner class executed….");
   }
  }; in .fun();
 }
}

Output:

Anonymous Inner class executed….


Found This Page Useful? Share It!
Get the Latest Tutorials and Updates
Join us on Telegram