A java program may consist of a number of packages.
A package may have a number of classes. For the time being, our program is made of only one package, which is nameless package.
Access Control is to control access to a member in a class. The control is given on two stages. One is on a class. The other is on a member.
This access control is provided by giving access modifiers to member and to class. For a class there are two kinds of modifier, public or no-modifier. For a member, there are four modifiers, public, no-modifier, protected and private. For the time being, we do not consider protected.
To access to a member in a class from other packages, both of class and member must be public. Access to a public member in a public class is always possible. It is possible from anywhere.
To access to a member in a class from a different class in the same package, class and member must be either with public or no-modifier. Access to a member in a class from within the same class is always possible. This means that to prohibit access to a member in a class from a different class, the member must be private.
Here is a sample program to demonstrate the access control.
B.java
class A{ public int X; private int Y; void setY(int yy) { Y=yy; } void show(){ System.out.println("X=" + X + "Y="+Y); } } class B{ public static void main(String args[]) { A a1=new A(); a1.X=1; //a1.Y=2; a1.setY(2); a1.show(); } } /* X=1Y=2 Since X in A is public, a1.X=1 is possible. But Y in A is private, so a1.Y=2 is not allowed. Therefore void setY(int yy) is made to set Y in A. */