Will the compiler-generated default constructor be public?

隐身守侯 提交于 2019-12-01 01:54:26

问题


When I write a class Widget.java

public class Widget {
    int data;
    String name;
}

will the compiler-generated constructor be public or default?

public would be like

public class Widget {
    int data;
    String name;
    public Widget() {}
}

whereas default similar to

public class Widget {
    int data;
    String name;
    Widget() {}
}

回答1:


It depends on your class visibility.The compiler uses the class visibility and generates a no-arg default constructor with the same visibility




回答2:


As said in JLS

If a class contains no constructor declarations, then a default constructor that takes no parameters is automatically provided:

  1. If the class is declared public, then the default constructor is implicitly given the access modifier public;
  2. If the class is declared protected, then the default constructor is implicitly given the access modifier protected;
  3. If the class is declared private, then the default constructor is implicitly given the access modifier private;
  4. Otherwise, the default constructor has the default access implied by no access modifier



回答3:


As classes visibility is public, it will always be a public constructor.




回答4:


It will be public as the class visibility is public

public Widget() {}



回答5:


It will be public Widget() {}




回答6:


Depends on class visibility. For your class dafault constructor is going to be public.

In a class type, if the class is declared public, then the default constructor is implicitly given the access modifier public (§6.6); if the class is declared protected, then the default constructor is implicitly given the access modifier protected (§6.6); if the class is declared private, then the default constructor is implicitly given the access modifier private (§6.6); otherwise, the default constructor has the default access implied by no access modifier.

From here.




回答7:


If your class is public then the default constructor would be public so in your case, Since the Widget class is public its default constructor supplied by the compiler would also be public. See this



来源:https://stackoverflow.com/questions/21750609/will-the-compiler-generated-default-constructor-be-public

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