What's the access modifier of the default constructor in java?

寵の児 提交于 2019-11-29 21:23:44

I thought its access modifier is public, but when I deal with a inner class issue, I found maybe I was wrong.

Yup. Indeed, I found myself in the same situation a couple of years ago. I was surprised by an error (through Guice injection, which made it slightly harder to find).

The key is to check the spec, in this case section 8.8.9:

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.

So in this case, your constructor is implicitly protected.

In addition to what Jon pretty well stated, here is an image example, for the visual guys.

If there is no constructor in a class, compiler automatically creates a default constructor.

Here is an example that successfully depicts the above rule:

For further reference, please refer here.

I would like to point out one more thing that I recently got. If you define a default constructor for your class then it's acess specifier will be what you assign. For example,

 public class A{
       A(){
       // do some stuff
       }
    }

Here the access specifier of the default constructor is package access and not public access (that of the class). However

 public class A{
       // no constructor is defined
    }

Here the compiler will sympathize with you and give you a default constructor whose access specifier will be same as the class , that is public.

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