简体   繁体   中英

what is java 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 ?

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, 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.

new is a keyword which has it's own syntax (as you have noticed). See JLS 3.9

Java doesn't have functions as such. It has methods and Java 8 will add more functional features.

It would be B b = a.new B(); and new is still just a keyword. The reference to the object a shows the compiler that B is a nested class. http://docs.oracle.com/javase/tutorial/java/javaOO/nested.html

B b = A.new B(); // A should be an instance object not a class name,
                 // otherwise it's not a valid syntax

You are creating an object of type B that would have access to instance members of the instance A .

The new is for sure a key word in Java.

This is part of new key word syntax. That have two way of invocation, as you have presented. The second is used to instantiate the outer class first before you can instantiate inner class.

It true that might look like a property of class, but you will not be able to create such property in Java. As 'new' is key word so it can not be used as property.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM