Question

Sometimes for testing I use quick "double-brace" initialization which creates anonymous nested class in Outer class, for example:

static final Set<String> sSet1 = new HashSet<String>() {
    {
        add("string1");
        add("string2");
        // ...
    }
};

Edit I am correcting my previously faulty statement that this example keeps reference to Outer instance. It does not and it is effectively equivalent to the following :

static final Set<String> sSet2;
static {
    sSet2 = new HashSet<String>() {
        {
            add("string1");
            add("string2");
            // ...
        }
    };
}

both sSet1 and sSet2 are initialized with anonymous nested classes that keep no reference to Outer class.

Does it mean that these anonymous classes are essentially static nested classes ?

Was it helpful?

Solution

As in the related question you are referencing to is discussed, an anonymous class cannot be static technically, but it can be so called effectively static if it is declared in a static context, that is it has no reference to the outer instance.

In your case, however, there is definitely no difference between two approaches, the initialization of static fields is a static context as well.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top