Protected Constructor Example Java

A Java constructor can be anyone one of the four access specifiers Java supports – public, protected, default and private. An examples on Protected Constructor is given with screenshots.
public class Demo
{
  protected Demo() 
  {
    System.out.println("Hello 1");
  }      
  public static void main(String args[])
  {
     Demo d1 = new Demo();
  }
}

Protected Constructor

Replace protected with private, default and public, still the program works.

Salient points with private and protected constructors

  1. private constructor is accessible in its own class where defined. A class with private constructor cannot be inherited by other classes. Used in Singleton design pattern. Used for extra security provision not to allow the instantiation in other classes.
  2. Default constructor is accessible within the same class and also for all the classes within the same package.
  3. protected constructor can be accessed from its own class, its subclasses, all other classes belonging to the same package and subclasses of other packages.
  4. public constructor can be accessible from anywhere.
  5. EJB3 specification says the entities should have either a no-argument protected or private constructor.
  6. A class with both private and protected constructors available can be inherited; but subclass has the accessibility for protected constructors only.

The same restrictions of general access specifiers are applied for constructors also.

The 6th and the last point in the above list is given in example form. The code compiles, executes successfully and observe the screenshot for be sure.

class Test
{
  private Test() 
  {
    System.out.println("Hello 1");
  }      
  protected Test(int x) 
  {
    System.out.println(x);
  }      
}

public class Demo extends Test 
{       
  public Demo() 
  {
    super(100);
  }      
  public static void main(String args[])
  {
     Demo d1 = new Demo();
  }
}

Protected Constructor

4 thoughts on “Protected Constructor Example Java”

Leave a Comment

Your email address will not be published.