Search Logic Blocks

Monday, August 10, 2020

Java: Static Inner Classes

Like a class can have both static and non-static variables, it can have static and non-static inner classes. We have already learnt about static variables and non-static variables. We have also learned about non-static inner class in earlier post - inner classes. As we know that static variables are class variables and they can be accessed directly through the class itself. We don't need to create the instance of class to access the static variable.

Static inner class is declared static same way as the static variables are declared using static keyword. Static inner class is also accessed through the outer class itself and its instance is created using new operator. Static inner class can only access static members of the enclosing class, not other members.
public class StaticClassDemo {
static int staticInt = 5;
int noStaticInt = 5;
static class staticInnerClass {
staticInnerClass() {
System.out.println("Creating Static Inner Class");
}

void printText() {
System.out.println("Inside Static Inner Class");
}

void getOuterClassData() {
System.out.println("Outer Class Static Variable staticInt = " + staticInt);

// Can't access non-static members
//System.out.println("Outer Class Non-Static Variable noStaticInt " + noStaticInt);
}
}

public static void main(String[] args) {
StaticClassDemo.staticInnerClass stClass = new StaticClassDemo.staticInnerClass();

stClass.printText();
stClass.getOuterClassData();
}
}
Note: The code can be accessed here at Github Link.

No comments: