Java constructor having broader access level than its class

Deadly 提交于 2019-12-01 07:10:17

问题


Java specification allows a class with default access to have its constructor public access, what is the purpose of it, since it cannot be referenced outside its package?


回答1:


I wanted to make this a comment, but since no code tags are allowed in comments....

In regards to your comment on CristopheDs answer:

package bob;

class MySuperHiddenClass {

  public MySuperHiddenClass() {
        System.out.println("bob");
  }
}

And

package bob;
public class MyPublicClass extends MySuperHiddenClass {

}

No constructor was declared in MyPublicClass, but you can still call new MyPublicClass from any package.




回答2:


If you are asking for why you can have public constructors: it's because you can for example call them explicitely (or implicitely) when you extend a base class.




回答3:


Class visibility determines how the outside world create instances of the class. hence package private classes can only be instantiated within the package they are declared. method visibility (including constructors) determines how the instance, already instantiated can be used outside its class definition.

If you declare a package private class, with a private/protected construtor, how will you instantiate it from another class in the same package?

Two things: class visibility - determines how instances are created outside their defining packages. method visibility (including constructors) - determine how the access to the members are controlled, regardless of package visibility.



来源:https://stackoverflow.com/questions/10547317/java-constructor-having-broader-access-level-than-its-class

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