static nested classes in Java

When a nested class is prefixed with static, it is said as static nested classes in java. static nested class is similar to the static methods or variables in a class which can be accessed directly without creating an object for outer class.

General Syntax

class Outer_class{

static class Inner_class {

//statements

}

}


We may access static class by calling directly using outer class name, but its members or methods may not be accessed directly.

We can access the inner class by

Outer_class_name.Inner_class_name


We may have to create objects to access non-static members or methods which are inside the static inner class.

To create a object for a static nested class

Outer_class.Inner_class inner=new Outer_class.Inner_class inner();

where Outer_class.Inner_class - references the inner class directly from outer class without creating an object for outer class.

Example

class Plant{

static class Leaf{

void shakes(){

System.out.println("Leaf is shaking");

}

}

public static void main(String args[]){

Plant.Leaf l1=new Plant.Leaf();

l1.shakes();

}

}

Output

Leaf is shaking


We don't need to create objects to access static members or methods which are inside the static inner class.

Example

class Plant{

static class Leaf{

static void shakes(){

System.out.println("Leaf is shaking");

}

}

public static void main(String args[]){

Plant.Leaf.shakes();

}

}

Output

Leaf is shaking