Home:ALL Converter>What's the access modifier of the default constructor in java?

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

Ask Time:2014-02-25T15:14:14         Author:jason

Json Formatter

We all know that if we don't specifically define a constructor, the compiler inserts an invisible zero-parameter constructor. I thought its access modifier was public, but in dealing with an inner class issue, I found maybe I was wrong. Here is my code:

public class Outer {
  protected class ProtectedInner {
    // adding a public constructor will solve the error in SubOuterInAnotherPackage class
    //public ProtectedInner() {}
  }
}

And there is a subclass of Outer in another package:

public class SubOuterInAnotherPackage extends Outer {
  public static void main(String[] args) {
    SubOuterInAnotherPackage.ProtectedInner protectedInner 
      = new SubOuterInAnotherPackage().new ProtectedInner(); // Error!! Can't access the default constructor
  }
}

You will get an error in the main() method, but if you add a public constructor to the ProtectedInner class, that error is solved. That's why I'm thinking that the modifier of the default constructor is not public! So could anyone tell me what the access modifier of the default constructor is?

Author:jason,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/22007143/whats-the-access-modifier-of-the-default-constructor-in-java
Jon Skeet :

\n I thought its access modifier is public, but when I deal with a inner class issue, I found maybe I was wrong.\n\n\nYup. 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).\n\nThe key is to check the spec, in this case section 8.8.9:\n\n\n 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.\n\n\nSo in this case, your constructor is implicitly protected.",
2014-02-25T07:16:26
teobais :

In addition to what Jon pretty well stated, here is an image example, for the visual guys.\n\n\n If there is no constructor in a class, compiler automatically creates a default constructor.\n\n\nHere is an example that successfully depicts the above rule:\n\n\n\nFor further reference, please refer here.",
2016-01-18T13:33:45
yy