Access Modifier in Java


As you know, encapsulation links the data to the code that manages it. However, encapsulation provides another important feature: access modifier. Java access modifier is public, private, and protected. Java also defines a default access level. Protected only applies when inheritance is involved. The other access modifier is described later.


Let's begin by defining public and private. When a member of a class is modified by the public, then that member can be accessed by any other code, When a member of a class is specified as private, but that member can only be accessed by other members of his class. Now you can understand why the main () method was always followed by the public modifier. When no access modifier is used, then by default a class member is public within its own package but cannot be accessed outside its package.

In still developed classes, all members of a class use the default access mode. However, this is not what you would normally want to be the case. Typically, you want to restrict access to a class of data members - only allow access through methods. Also, there will come a time when you will want to define such practices in class.

Example

Program
//This program demonstrates the difference between public and private.
class Test
{
  int x; //default access
  public int y; //public access modifier
  private int z; //private access modifier
  void setz(int i)
  {
   this.z=i;
  }
  int getz()
  {
   return this.z;
  }
}
public class Main 
{
  public static void main(String[] args) 
  {
    Test obj=new Test();
    
    //There are OK, a and b may be access directly
    obj.x=5;
    obj.y=10;
    
    //This is not OK and will cause an error
    //obj.z=15; //Error
    
    //You must access c through its methods
    obj.setz(15);
    System.out.println("x, y, and z: "+obj.x+" "+obj.y+" "+obj.getz());
  }
}


As you can see, inside the Test class, "x" uses default access, which for this example is the same as specifying public. "y" is explicitly specified as public. Member "z" is given private access. This means that the private access modifier cannot be accessed by code outside its class. So, inside the "Main" class, "z" cannot be used directly. It must be accessed through its public methods: setz() and getz(). If you remove the comment symbol from the beginning of the following line,

//obj.z=15; //Error


In the next tutorials, there is a detailed description of the Protected Access Modifier.