Java Man
Java Man

Reputation: 43

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?

Upvotes: 4

Views: 88

Answers (1)

Pradyumna
Pradyumna

Reputation: 1633

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 :)

Upvotes: 4

Related Questions