Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 845
Kolodez Avatar asked Dec 15 '20 08:12

Kolodez


1 Answers

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.

like image 146
Andreas Avatar answered Oct 05 '22 23:10

Andreas