3

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 ?

kiruwka
  • 9,250
  • 4
  • 30
  • 41

1 Answers1

3

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.

Dmitry Tikhonov
  • 301
  • 1
  • 8
  • +1 Yes, you are right about no difference, I completely overlooked that. Could you please give some practical difference between *effectively static* and normal *static nested* class. Tom referenced `JLS 3rd Ed` for this in his answer(to which I refer), but may be you could put quick summary for me ? thanks. – kiruwka Dec 15 '13 at 19:13
  • After reading all answers to [this](http://stackoverflow.com/questions/758570) question, I realize that there is no technical difference, other then doing it is not really recommended as this Java feature could be pulled out. – kiruwka Dec 15 '13 at 19:45