开发者

What is inner creator (objectinstance.new) in Java?

开发者 https://www.devze.com 2023-03-03 12:48 出处:网络
I came across something like ArgProcessor argProcessor = runWebApp.new ArgProcessor(op开发者_如何学JAVAtions);

I came across something like

ArgProcessor argProcessor = runWebApp.new ArgProcessor(op开发者_如何学JAVAtions);

This line is from the source of GWT. By digging into Java's grammar I found it to be (".new") inner creator.

But I didn't find any proper documentation about why exactly we need the inner creator.

How does this differ from a normal object/instance creator?


It is for creating an object of the inner class type.

for example: look at this

http://www.javabeat.net/tips/124-inner-classes-in-java.html

ie:

class Outer{

  final int z=10;

  class Inner extends HasStatic {
    static final int x = 3;
    static int y = 4;
  }

  public static void main(String[] args) {
    Outer outer=new Outer();
    System.out.println(outer.new Inner().y);
  }
}


The new keyword in this example is called within the scope of the runWebApp instance. This means that runWebApp.class contains an inner class called ArgProcessor. This is the appropriate way to specify you are construction ArgProcessor within runWebApp, and not calling some other top level ArgProcessor class.

Note that the external assignment will have an instance of ArgProcessor, but it will be runWebApp's instance of ArgProcessor, and not some other instance's ArgProcessor instance. Occasionally, this is done to simulate an old style C++ friend interface between classes; however, there are other reasons why this might be done. It basically allows a more fine grained approach than the standard public, protected, default, private interfaces available with the actual programming language.


An inner class is a class defined in another class. If it is not static, each instance of an inner class has an implicit reference to the instance of the outer class. It can be accessed from within the inner class like this: OuterClass.this.

So, when you instantiate the inner class InnerClass from a non static method of the instance outerObject of the outer class OuterClass, the created instance innerObject has an implicit reference to outerObject. But when you want to do the same from somewhere outside of OuterClass (or from a static method), you have to specify the instance of OuterClass it will reference: you do that by calling new on the instance of the outer class.

0

精彩评论

暂无评论...
验证码 换一张
取 消