How to Work Data Permission Control in Java3 min read

In this article we will look at access control in Java. We will learn about four access modifiers: public, protected, default and private along with java code examples.

Access Control

Access control is a mechanism, an attribute of encapsulation which restricts the access of certain members of a class to specific parts of a program. Access to members of a class can be controlled using the access modifiers.There are four access modifiers in Java. They are:

  1. public
  2. protected
  3. default
  4. private

If the member (variable or method) is not marked as either public or protectedor private, the access modifier for that member will be default. We can apply access modifiers to classes also. Among the four access modifiers, private is the most restrictive access modifier and public is the least restrictive access modifier. Syntax for declaring a access modifier is shown below:

access-modifier  data-type  variable-name;

Example for declaring a private integer variable is shown below:

private int side;

In a similar way we can apply access modifiers to methods or classes although private classes are less common.

Note: Packages and inheritance will be discussed in another article in future. So, I will defer the explanation of protected to packages article as protected is useful only when there is inheritance.

What is the use of access modifiers?

As I had said above, access modifiers are used to restrict the access of members of a class, in particular data members (fields). Let me explain this through Java code. Let’s consider an employee class as shown below:

By looking at the above code we can say that the access modifier for all the three data members is default. As members with default (also known asPackage Private or no modifier) access modifier are accessible throughout the package (in other classes), a programmer might, by mistake, try to make an employee’s salary negative as shown below:

Although above code is syntactically correct, it is logically incorrect. To prevent such things to happen, in general, all the data members are declared privateand are accessible only through public methods. So, we can modify ourEmployee class as shown below:

By looking at the above code, we can say that one can access the salary field only through setSalary() method. Now, we can set the salary of an employee as shown below:

The modified Employee class is the best way of writing programs in Java.

Take your time to comment on this article.

Leave a Comment