Kolodez
Kolodez

Reputation: 635

How to create a Java inner class correctly?

I have the following java classes:

public class Outer {
 ...
 private class Inner {
  ...
 }
 ...
}

Assume I am inside a non-static method of Outer. Does it make a difference whether I call this.new Inner() or new Outer.Inner()? Is it, in the second case, guaranteed that no new Outer is created?

I have an annoying error in my program that appears only sometimes and is hard to find or to reproduce. So I am wondering if this line could make any problems.

Upvotes: 5

Views: 205

Answers (1)

Andreas
Andreas

Reputation: 159086

They are the same, though they are both unnecessarily long-winded.

The following 3 versions results in the exact same bytecode:

class Outer {
    private class Inner {
    }
    void foo() {
        Inner a = this.new Inner();
        Inner b = new Outer.Inner();
        Inner c = new Inner();       // Recommended way to write it
    }
}

Bytecode

       0: new           #7                  // class Outer$Inner
       3: dup
       4: aload_0
       5: invokespecial #9                  // Method Outer$Inner."<init>":(LOuter;)V
       8: astore_1

       9: new           #7                  // class Outer$Inner
      12: dup
      13: aload_0
      14: invokespecial #9                  // Method Outer$Inner."<init>":(LOuter;)V
      17: astore_2

      18: new           #7                  // class Outer$Inner
      21: dup
      22: aload_0
      23: invokespecial #9                  // Method Outer$Inner."<init>":(LOuter;)V
      26: astore_3

Blank lines added to improve clarity.

Upvotes: 7

Related Questions