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 ?

6
  • Your first example doesn't have a reference to Outer or am I missing something? Commented Dec 15, 2013 at 18:22
  • @SotiriosDelimanolis Well, I believe anonymous inner class from first example does contain implicit reference to Outer.this Commented Dec 15, 2013 at 19:00
  • 1
    No, it doesn't. You're in a static context in both. There is no outer instance. Commented Dec 15, 2013 at 19:02
  • @SotiriosDelimanolis Right, stupid me, sorry. Commented Dec 15, 2013 at 19:08
  • Lol, that's a little harsh. Usually, I'll try this in my IDE Outer.this.someMethod(). If it doesn't compile, then gotta rethink my logic. Commented Dec 15, 2013 at 19:09

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

+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.
After reading all answers to this 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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.