Java Nested Classes

In java you can write a class inside another class as its member. The class which holds the inner class is called outer class and the class written inside is called nested class. We cannot define a class as private in java but the nested class can be made private.The nested class can access all the members of the outer class including private members so it can be used as a security mechanism.

Syntax

class OuterClass{

//outer class body

class NestedClass{

//nested class body

}

//outer class body

}

Types of Nested Classes

  1. Non-static nested class
    • Inner Class
    • Method-local Inner Class
    • Anonymous Inner Class
  2. Static Nested Class

Inner Class

A class written inside body of another non-static class outside method is called inner class. See the inner class below.

class OuterClass{

private class InnerClass{

public void printHello(){

System.out.println(“I am in inner class”);

}

}

void innerHello(){

InnerClass inner = new InnerClass();

inner.printHello();

}

}

public class JavaNestedClass{

public static void main(String args[]){

OuterClass outer = new OuterClass();

outer.innerHello();

}

}

Method-local Inner Class

A class written inside method of outer class is called method-local inner class. See the method-local inner class example below.

public class JavaNestedClass{

void outerClassMethod(){

//the method-local inner class

class MethodInnerClass{

public void printHello(){

System.out.println(“I am in method-local inner class”);

}

}

//Accessing method-local inner class
MethodInnerClass inner = new MethodInnerClass();

inner.printHello();

}

public static void main(String args[]){

JavaNestedClass outer = new JavaNestedClass();

outer.outerClassMethod();

}

}

Anonymous Inner Class

The anonymous inner class in java is a class written inside body of outer class without class name. The class name is decided by compiler at compile-time. It can be used for extending classes and implementing interfaces.

AnonymousClass inner = new AnonymousClass(){

//anonymous class body

};

Static Nested Class

A class written inside another class as static is called static nested class. See the static nested class example below.

public class JavaNestedClass{

static class NestedClass{

public void printHello(){

System.out.println(“I am in static nested class”);

}

}

public static void main(String args[]){

JavaNestedClass.NestedClass inner = new JavaNestedClass.NestedClass();

inner.printHello();

}

}

Leave a Reply

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