Access Specifiers -


Java has four access specifiers - public, private, protected and default.
1- public - public access specifier provide the widest possible visibility level. A public member is accessible everywhere regardless of package.
2- protected - protected members can be accessed in any class within the same package and inheriting classes i.e. subclasses in other packages.
3- default - If any member does not have any access specifier defined then by default it will have default access specifier. Default members can be accessed by any classes but classes should be within the same package.
4- private - private members are accessible only within the class in which they are defined.

Example -

package A;
class First
{
    private int a=1;
            int b=2;
    protected int c=3;
    public int d =4;
}
public class Demo
  {
      public static void main(String[] args)
      {
          First f1 = new First();
        //System.out.println(f1.a);  //Not accessible because a is private
          System.out.println(f1.b);
          System.out.println(f1.c);  //accessible b/c both classes are in the same package
          System.out.println(f1.d);
          
      }
  }


package B;
class Second extends A.First
{
    public Second()
    {
       //a =10; //Not accessible because a is private.
      // b =20;  //Not accessible because default members are not accessible in other package.
          c =30;  // Accessible because 'Second' class is inheriting the class 'First' 
         d =40;   // Accessible, public members are always accessible everywhere.
    }
}
                     
Note :- protected members (c variable in our example) can be accessed in any class within the same package (as in class 'Demo') and inheriting classes i.e. subclasses in other packages (as in class 'Second'). But they will not be accessible in classes those exist in some other packages, and classes there do not inherit the class containing protected members.