Private Access Applied to a Constructor

When the private access modifier is applied to a constructor, the following access is granted:

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

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 private access, other constructors can be public, default, or protected access.
  • It is common to invoke a private access constructor from within the same class using a constructor with less restrictive access.


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;

// class Tester extends ConstructorOne { // Inheritance
class Tester { // extends Tester - If we try inheritance we will get a cyclic relationship error

    private Tester() { 
        super();
        System.out.println("Invoked the private Tester() constructor.");
    }

    public static void main(String args[]) {
        Tester t = new Tester(); // we can create an instance of Tester using a private constructor from within the same class
        // ConstructorOne co = new ConstructorOne(); // Reference
        // ConstructorOne co = new ConstructorOne("Whatever");
    }
}

class ConstructorOne {
    private ConstructorOne() { 
        super(); 
        System.out.println("Private constructor in ConstructorOne!");
    } 

    ConstructorOne(String doesNotMatter) { 
        this(); 
    } 
}

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


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


Final thoughts

There was no need to test the private modifier on a constructor outside of a package. The private modifier is irrelevant when it comes to packages.


Tutorials