Avoid Package with One class By Static Nested Class


java static nested class, static inner class.

In the previous post, we discussed on inner class for “one and only for” relationship among the classes. But static nested class not for same purpose, it is to add namespace to the class.  It can be instantiated just with top class name (without top class instance).  Static nested class is class scoped within another. So with static classes it’s really more about namespace resolution. So the inner static classes accessed with outer class name.

Try to avoid creating new package only for one class by Static Nested Class.

Package provides grouping of logical related class with name such as “info.javaarch.beans”. But creating a new package for only one class can be avoided by static nested class. Logically associate the class with other class with “static” keyword.   So it has to be accessed with outer class name like package and it would avoid creating new package for only one class. Let us take an example,

package info.javaarch;

public class StaticInnerClass {

public static void main(String args[]) {

System.out.println(Math.Constants.PI);  // Accessing  the static nested class Constants with Math name

}

}

class Math{     // outer class

static class Constants{                  // Static nested class
public static Float PI = 3.14f;
public static String LOG = “LOG2”;
public static String ADD = “+”;
public static String SUB = “-“;

}

}

“Constants” class has static variables for math operation. It is nested class of Math class. It has to be accessed as “Math.Constants”. So it gives more information such as this constants related to math operation.

Math.Constants.PI is more meaningful than Constants.PI

In the above example, we can write new package info.javaarch.constants package with class “Constants.java”.  We want to avoid package with one class, so create the static class inside Math(which logically correct). We avoided that creating new package,at the same time we access the constants with namespace Math.Constants.

Points to remember for static nested class:
  • Static nested classes are inner classes marked with the static modifier.
  • A static nested class is not an inner class, it’s a top-level nested class.
  • Because the nested class is static, it does not share any special relationship with an instance of the outer class. In fact, you don’t need an instance of the outer class to instantiate a static nested class.
  • Instantiating a static nested class requires using both the outer and nested class names as follows:
    Math.Constants MC = new Math.Constants();
  • A static nested class cannot access non-static members of the outer class, since it does not have an implicit reference to any outer instance.

Discussed member inner class and static nested class in details with examples. Kindly share if you have comments on inner class. Happy Learning:)

You may also like