Default (Package-Private) Access Applied to a Constructor

When no access modifier exists in a constructor declaration, the following default (package-private) access is granted:

  • Full access is granted to invoke the constructor from within the same package.

Things to think about

  • Multiple overloaded constructors can have different types of access modifiers applied to them. In other words, if you have one constructor with default access, other constructors can be public, protected, or private access.
  • Be mindful of the class access type. A standard outer class can only have either public or default access. A default access constructor within a public access class may cause compiler errors.


Open the command prompt (CMD - see the Getting Started ) and type in the following commands.

C:\Windows\System32>cd \
C:\>md Java
C:\>cd Java
C:\Java>
C:\Java>md one
C:\Java>cd one
C:\Java\one>Notepad ConstructorOne.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


package one;

import two.*;

// class Tester extends ConstructorTwo { // error
class Tester {

    public static void main(String args[]) {
        new ConstructorOne(); // from package one
        //new ConstructorTwo(); // from package two - error
    }
}

class ConstructorOne {

    ConstructorOne() { 
        super(); 
        System.out.println("Default constructor in package ONE!");
    }
 
}

Now switch back to the command prompt (CMD) and type in the following commands.


C:\Java\one>cd ..
C:\Java>md two
C:\Java>cd two
C:\Java\two>notepad ConstructorTwo.java

Copy and Paste, or type the following code into Notepad and be sure to save the file when you are done.


package two;

public class ConstructorTwo {

    ConstructorTwo() { 
        super(); 
        System.out.println("Default constructor in package TWO!");
    }
      
}

Now switch back to the command prompt (CMD) and type in the following commands.


C:\Java\one>cd ..
C:\Java>javac one\ConstructorOne.java
C:\Java>java one.Tester // play around with uncommenting and comment various statements.
Varying results


Final thoughts


Tutorials