HTML Java

Java Nested Classes


Java Nested Classes or Java Inner classes

This class can be declared private, public, protected, or with default whereas outer class can be declared only public or default.

When we declare a class inside another class or interface called nested class.

Example

class Student
{
String name; int age;
class Address {
String city, state, country;
}
}

Type of Nested class:

  • Static-Nested-Class
  • Non-Nested-Class
  • Local-Nested-Class
  • Anonymous-Nested-Class

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 of Inner class

class Java_Outer_class {
//code class Java_Inner_class {
//code
}
}


Advantage of java inner classes

  • 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.
  • Nested classes are used to develop more readable and maintainable code because it logically group classes and interfaces in one place only.
  • Code Optimization: It requires less code to write.

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)
  • Member inner class
  • Anonymous inner class
  • Local inner class
  • Static nested class

Syntax to create static nested class:

OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();


Syntax to create inner class

OuterClass outer = new OuterClass();
OuterClass.InnerClass innerClass = outer.new InnerClass();

Example of above the types of Inner class

import java.util.Arrays;

public class InnerClassTesting {

public static void main(String[] args) {

OuterClass outer = new OuterClass(5,6,7,8);

//static nested classes example
OuterClass.StaticNestedClass staticNestedClass = new OuterClass.StaticNestedClass();

System.out.println(staticNestedClass.getName());
staticNestedClass.d=10;
System.out.println(staticNestedClass.d);

//inner class example
OuterClass.InnerClass innerClass = outer.new InnerClass();
System.out.println(innerClass.getName());
System.out.println(innerClass);
innerClass.setValues();
System.out.println(innerClass);

//calling method using local inner class
outer.print("Outer");

//calling method using anonymous inner class
AnonymousInner inner = new AnonymousInner() {
public void myMethod() {
System.out.println("This is an example of anonymous inner class");
}
};
inner.myMethod();
}

}
Try it »

This is an example of anonymous inner class.