简体   繁体   中英

How do classes instantiate in Java?

I came accross the following rule in JLS8/15.9.1 :

The Identifier after the new token must unambiguously denote an inner class that is accessible, non-abstract, not an enum type, and a member of the compile-time type of the Primary expression or the ExpressionName .

I can't imagine what it the last restriction means. Maybe you can give an example of such a member of the compile-time type of the Primary expression of the ExpressionName ?

It says "If the class instance creation expression is qualified" .. then .. (your quotation)

So, I guess it's this case:

package test;

public class Test1 {
    public class Test3{

    }
}

And you instantiate it in another class like this:

package test;

import test.Test1.Test3;

public class Maker {

    public static void main(String[] args) {
    Test1 test1 = new Test1();
        Test3 test3 = test1.new Test3();    
    }

}

Then,

  1. The instance creation expression is qualified: test1.new Test3() (test1.new, - a qualified new and not an unqualified new)
  2. The primary expression is test1
  3. The compile-time type of the primary expression is Test1
  4. The Identifier after the new token is Test3 and it unambiguously denotes the class Test3
  5. Test3 is accessible, non-abstract, not an enum type, and is a member of the compile-time type of Test1, the compile-time type of the primary expression.

Enjoy :)

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