« Generic confusion | Main

Wha? You can DO that?!?!

A co-worker came to me today with a Java question.

"What are the rules for instantiating a public inner class?", he asks. So, for example:

public class Outer {

    public class Inner() {

    }

}

"Well", I said knowingly, "the inner class instance cannot exist without a reference to an outer class instance." So far, so good. "So", I postulate, not realizing that I am horribly wrong, "you can only instantiate the inner class from with the outer class instance." Ummm...no. The following code actually compiles:

Outer.Inner inner = (new Outer()).new Inner();

We stared at the horrible, horrible syntax for a while, much the same way people stare at car crashes - terrified but unable to look away.

"Dot new?", I said incredulously.

"Dot new!", he said, completely disgusted.

"Can you refactor your code so you don't have to do this?", I said.

"I can sure as hell try", he said.