Static Nested Classes Tutorial

The static nested class is one of the four nested classes that I briefly discussed in my Introduction to Nested Classes tutorial. A static nested class is defined at the member level and must have the keyword static in the declaration.
class Standard {
     String s = "";
     static class StaticNested {
         int i = 0;
     }
}
The first thing to understand about an nested static class is that you do not need an instance of either the outer class or the nested static class in order to access its members. You can directly access static methods and variables without creating an object. If you would like to create an instance of a nested static class you do not need an instance of the outer class in order to do so.

Here are some rules for a static nested class:

  • A static nested class can access all static members of the outer class (even private).
  • A static nested class can have all levels of access applied (public, default protected) except for private.
  • A static nested class can be final or abstract, I don't know why you want to, but you can.
  • A static nested class can extend other classes and implement interfaces.



Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md StaticNestedClass
C:\Java>cd StaticNestedClass
C:\Java\StaticNestedClass>Notepad StaticNestedClass.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


class Tester {
    public static void main(String args[]) {
        Outer.StaticNested.displayS();

        //Outer.StaticNested os = new Outer.StaticNested();
        //os.displayS();
    }
}

class Outer {
    String s = "outer s";
    private static String t = "outer t";
    static class StaticNested {
        static String s = "nested s";
        static void displayS(){
            System.out.println(s);
            System.out.println(t);
            System.out.println(new Outer().s);
        }
    }    
}

Now switch back to the command prompt (CMD) and type in javac StaticNestedClass.java and press Enter.
Now type in java StaticNestedClass and press Enter.


C:\Java\StaticNestedClass>javac StaticNestedClass.java
C:\Java\StaticNestedClass>java StaticNestedClass
nested s
outer t
outer s


Final thoughts

None


Tutorials