• Encapsulation provides important attribute: Access Control
  • Through encapsulation, we can control what parts of a program can access the member of a class.
  • By controlling access, you can prevent misuse.
  • Access specifier determines how a member can be accessed.
  • Java’s access specifiers are as follow:
  1. Public:  When a member of a class is declared as public, it can be accessed by any other code.
  1. Private:When a member of a class is declared as private, it can only be accessed by other members of its class.
  1. Protected:A protected member can be accessed outside the current package, but only to derived subclass
  1. Default: When no access specifier is used, then by default the member of a class is public within its own package, but cannot be accessed outside of its package.
  • That’s why main (), has always been preceded by the public specifier.
  • It is called by the code outside of the program. (by java run-time system).
  • To understand the effects of public and private access considers the following program:
class Test
{
    int a;
    public int b;
    private int c;

    void SetC (int i)
    {
        c = i;
    }
   int getC()
   {
       return c;
   }
}

class AccessTest
{
	public static void main (String args[])
	{
	   Test ob = new Test();
	   ob.a = 10;
	   ob.b = 20;
	   //ob.c = 100;   // cause an error.
	   ob.SetC (100);
	   System.out.println("a, b and c: " + ob.a + " " +     ob.b  + " " + ob.getC()); 
	}
}
  • The Test class contains three data members of int type that e.i a, b and c.
  • here, b  is a public member, c is declared as private and a is of default type.
  • private members can not be accessed from outside the as it can only be accessed from the class itself in which it is declared.
  • so inside the main(), the following statement where we have tried to access private member will cause error because private member cannot be accessed from outside the class.
 //ob.c = 100;   // cause an error.
  • We can access private members using well defined member functions only.
  • In above example, we have setC() and getC() member functions to set and access private member ‘c’.
  • Data member b is of public type, it can be accessed from everywhere so it does not cause an error while trying to access it from the main() as follow:
 ob.b = 20;
  • Since data member a has default   access specifier, it is similar to public except that public member can be accessed from outside the package also while data member having default specifier  can’t be accessed from outside the package in which it is declared.
  • In short, anything declared as public can be accessed  from anywhere while private can not be accessed from outside of its class and anything declared as default can also be accessed from anywhere but inside the same package and not from outside the package.
  • One another access specifier is there which is protected but we will focus on it later as it has something to do with inheritance.