简体   繁体   中英

Why use Static Nested Classes in Java?

I am new to java and have been scratching my head understanding some its concepts. I am following the tutorial Java tutorial . However, I cannot find the usefulness of using Static Nested Classes. I mean I think I need some good examples as to why I should want to use it. Can someone provided me some codes as examples so I can understand it better? thax

The benefit of a static nested class over an "ordinary" class is that you can use it to reflect the relationship between two classes.

For example in the JDK there is java.util.Map and java.util.Map.Entry .

java.util.Map.Entry is declared as a public static interface and doing it this way clearly signposts its relationship to Map . It could have been defined as java.util.MapEntry but doing it as a static nested interface makes it clear that it has a strong relationship to Map .

So you'd probably only use static nested class when the nested class would only ever be used in the context of its parent.

The following example might not be for a Java beginner but one nice example of static nested class is when you want to use the Builder pattern to construct immutable objects of the outer class. The static nested class is allowed to access private members of the outer class thus constructing objects of the outer class although it has a private constructor and initializing private fields of the outer class. Eg

    public class SomeClass {
    private int someField;
    private int someOtherField;

    private SomeClass()
    {}

    public static class SomeBuilder {
        private int someField;
        private int someOtherField;

        public SomeBuilder setSomeField(int someField)
        {
            this.someField = someField;
            return this;
        }

        public SomeBuilder setSomeOtherField(int someOtherField) {
            this.someOtherField = someOtherField;
            return this;
        }

        public SomeClass build() throws ValidationException
        {
            validateFields();            

            SomeClass someClass = new SomeClass();
            someClass.someField = someField;
            someClass.someOtherField = someOtherField;
            return someClass;
        }

        private void validateFields() throws ValidationException {
            //Validate fields
        }
    }

    public int getSomeField() {
        return someField;
    }
    public int getSomeOtherField() {
        return someOtherField;
    }
}

Nested or inner class is just an ordinary class defined into other class. The reason to do this is typically to hide inner class from others, ie it is yet another level of encapsulation.

Inner class can be private, protected and public that mean exactly the same as for fields and methods.

If inner class is not private you can access it from outside too. Its name is OuterClass.InnnerClass . The nesting depth is not limited by Java specification, so inner class can have its own inner classes etc.

If inner class is not static it has yet another feature: ability to call outer's class methods and fields.

Inner class can be also anonymous. This is very useful for small callbacks, event handlers etc.

Hope this helps. Do not hesitate to ask other more concrete questions.

Another thing I should add is that if an inner class is not static, an instance of it will automatically have a reference to its parent class instance. You can reference it by using: NameOfOuterClass.this .

But if it is static, then it will not.

This, among other things, comes into play during GC (garbage collection). Because, if an object of the inner class is not being GCed, then the outer class object it references will not be GCed either (in cases where the inner class was not static).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM