Why Statefulness Exists Inside a Static Class in Java

javastatic

I was playing around with Java today and I read about static inner classes. Why can you have 'statefulness' inside of a static inner class. For instance:

class outerClass { 
        static class Test { 
        private String a; 

        String getA() { return a; } 

        void setA( String newA) {a = newA; } 

    }
}

Am I misunderstanding something? It seems like you should not be able to keep mutable state inside of a class that is labled at static. Moreover it seems like you should not be able to instantiate something that is a static class, it should be a static singleton. Perhaps someone could correct me if I am making an incorrect assumption or enlighten me to why the Java authors decided to make this possible.

EDIT: I feel as if I am confusing the keyword final and static in java, as final variables do not have state. It still seems very strange to be able to instantiate a static class, though.

Best Answer

A static inner class is the same as a non-inner class. Your example is equivalent to:

class outerClass {}

class Test {
    ...
}

The static in static inner classes means that instances of the inner class aren't associated with an instance of the outer class. Without static, an instance of Test is always attached to an instance of outerClass - you'd need to construct an instance of outerClass before you can construct an instance of Test and the instance of Test would have access to the members of outerClass.

Related Topic