What does `someObject.new` do in Java?

后端 未结 5 1606
灰色年华
灰色年华 2020-12-23 02:47

In Java, I have just found out that the following code is legal:

KnockKnockServer newServer = new KnockKnockServer();                    
KnockKnockServer.re         


        
5条回答
  •  醉酒成梦
    2020-12-23 03:05

    It's the way to instantiate a non-static inner class from outside the containing class body, as described in the Oracle docs.

    Every inner class instance is associated with an instance of its containing class. When you new an inner class from within its containing class it uses the this instance of the container by default:

    public class Foo {
      int val;
      public Foo(int v) { val = v; }
    
      class Bar {
        public void printVal() {
          // this is the val belonging to our containing instance
          System.out.println(val);
        }
      }
    
      public Bar createBar() {
        return new Bar(); // equivalent of this.new Bar()
      }
    }
    

    But if you want to create an instance of Bar outside Foo, or associate a new instance with a containing instance other than this then you have to use the prefix notation.

    Foo f = new Foo(5);
    Foo.Bar b = f.new Bar();
    b.printVal(); // prints 5
    

提交回复
热议问题