Protected Constructor Example Java

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.

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.

Protected Constructor

2 thoughts on “Protected Constructor Example Java

Leave a Reply

Your email address will not be published. Required fields are marked *