Protected Access Applied to a Constructor

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

  • Full access is granted to invoke the constructor from within the same package. In addition, access is granted to invoke the constructor from subclasses of another package through inheritance only.

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 protected access, other constructors can be public, default, or private access.
  • Be mindful of the class access type. A standard outer class can only have either public or default access.
  • A protected access constructor can be invoked (inheritance or reference) from within the same package irregardless of the class access.
  • A protected access constructor can only be invoked through inheritance outside of the package and only when it is contained in a public access class.


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 {
class Tester extends ConstructorOne {

    public static void main(String args[]) {
        ConstructorOne co = new ConstructorOne(); // from package one - reference
        Tester t = new Tester(); // Inheritance
        //ConstructorTwo ct = new ConstructorTwo(); // from package two - reference
  
    }
}

public class ConstructorOne {
    protected ConstructorOne() { 
        super(); 
        System.out.println("Protected 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 {
    protected ConstructorTwo() { 
        super(); 
        System.out.println("Protected 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

It would take a very rare, very special circumstance to warrant the use of a protected constructor.


Tutorials