java

What is Java's 'new'? A function or keyword


As I understand, new is a keyword and not a function.

For example

A a = new A();

instantiates the object a of type A.

A keyword is not associated with any object per se.

On the contrary, when we have in A a public inner class B we call

B b = a.new B()

Here it looks like new is a property of B and not an independent keyword.

What is the meaning of A.new?


Solution

  • new is a keyword in both cases. It's part of a class instance creation expression.

    There are two forms: unqualified and qualified.

    The unqualified form starts with the keyword 'new'.

    The qualified form starts with a primary class, and then 'new'. This allows creation of inner classes—non-static nested classes that hold an implicit reference to an instance of the outer class. The qualified form provides a way to specify that instance.

    From the Java Language Specification, section 15.9:

    Unqualified class instance creation expressions begin with the keyword new.

    An unqualified class instance creation expression may be used to create an instance of a class, regardless of whether the class is a top level (§7.6), member (§8.5, §9.5), local (§14.3) or anonymous class (§15.9.5).

    Qualified class instance creation expressions begin with a Primary.

    A qualified class instance creation expression enables the creation of instances of inner member classes and their anonymous subclasses.