Do default constructors for private inner classes have a formal parameter?

☆樱花仙子☆ 提交于 2019-12-03 01:26:38

There is a difference between the implementation and the specification.

In my opinion the "except" JLS statement

...except in a non-private inner member class...

is poorly worded.

It means, the compiler is not required to implicitly declares one formal parameter representing the immediately enclosing instance of the class... but it could.


Why implicitly formal parameter is required in non-private inner member class ?

From JLS 8.8.1:

The member class may have been emitted by a compiler which is different than the compiler of the class instance creation expression. Therefore, there must be a standard way for the compiler of the creation expression to pass a reference (representing the immediately enclosing instance) to the member class's constructor

For example if i compile this inner class with a first compiler:

package p1;
public class Ctors {
    public class MyInner {
    }
}

if i want to compile this sub class with another compiler:

package p2;

import p1.Ctors;

public class SubCtors {
    public SubCtors() {
        new Ctors();
    }
}

the second compiler must be able to use the default constructor with the formal parameter. In this case the instance of the enclosing class with a SubCtors instance.


Why implicitly formal parameter is not required in non-private inner member class ?

Because a non-private inner member class is always accessed by the same compiler that compiled it. As you shown, javac generates the same constructor regardless to the class visibility but it is not require to. Another compiler implementation is free to choose another way.

There is also another point in JLS 8.8.1 which is very much along the same line

In a class instance creation expression for a local class (not in a static context) or anonymous class, §15.9.2 specifies the immediately enclosing instance of the local/anonymous class. The local/anonymous class is necessarily emitted by the same compiler as the class instance creation expression. That compiler can represent the immediately enclosing instance how ever it wishes. There is no need for the Java programming language to implicitly declare a parameter in the local/anonymous class's constructor.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!