Java - Access Level Modifier for a Constructor

Why access control on constructor

Access level for a constructor controls from where the program can access constructor.

You can specify one of the four access levels for a constructor:

  • public,
  • private,
  • protected, and
  • package-level.

Rule

Level Access Control
public, a public access level can be used in any part of the program.
private,private access level can be used only inside the same class in which it is declared.
protected, and protected access level can be used in any part of the program in the same package and inside any descendant class in any package.
package-level. package-level access can be used inside the same package in which its class is declared.

Example

The following code declares four constructors for the Test class.

public class Test {
        // Constructor #1 - Package-level access
        Test() {
        }
        // Constructor #2 - public access level
        public Test(int x) {
        }

        // Constructor #3 - private access level
        private Test(int x, int y) {
        }

        // Constructor #4 - protected access level
        protected Test(int x, int y, int z){
        }
}

Because the class Test has a public access level, you can declare a reference variable of type Test as shown below anywhere in the program:

Test t;//Code inside any package

Because the constructor for the class Test has a public access level, you can use it in an object creation expression in any package.

new Test();//Code inside any package

You can combine the above two statements into one in the code in any package.

Test t = new Test(); //Code inside any package

Related Topic