Saturday, January 11, 2020

Java access modifiers

Access Modifiers


Access modifiers are used to control the visibility and availability. There are two levels of access control in Java.
At the top level, we can use an access modifier before the name of any class or interface. There are two access specifiers possible at this level.
  1. public:- Available within its own and other packages.
  2. No access specifier:- Available within its own package only.
At the lower level,  or the class member level, any member of the class can have any of the four access specifiers.
  1. public:- Available within its own and other packages.
  2. protected:- Available within its own class, package and subclasses. All protected members become private within the subclass of the declaring class.
  3. No specifier:-Available within its own package.
  4. private:- Available within its own class only.
We can take an example to understand the access specifiers in Java. Let, there are two packages named one and two, and four classes A, B, C, and D.  A and B are in package one. C and D are in package two. X is the subclass of A.
access specifiers in Java


TABLE FOR ACCESS SPECIFIERS


A
B
X
Y
 public  
Y
Y
Y
Y
protected
Y
Y
Y
N
no specifier
Y
Y
N
N
private
Y
N
N
N








Example(access modifiers)

package one;
/**********class A***************/
public class A {
public int a;
protected int b;
int c;
private int d;

/*          TABLE FOR ACCESS SPECIFIERS
 * Class->        A     B     X     Y
 * public         Y     Y     Y     Y
 * protected      Y     Y     Y     N
 * no specifier   Y     Y     N     N
 * private        Y     N     N     N
 */
}
package one;
/************class B**************/
public class B{
      public void test()
      {
            A a=new A();
            a.a=12;  //Y
            a.b=13;  //Y
            a.c=14;  //Y
            //a.d=15;//N ||ERROR->d is not visible
      }
}
package two;

import one.A;
/************class X************/
public class X extends A{//X is subclass of A
      //ALL PROTECTED MEMBERS OF A WILL BECOME
      //PRIVATE IN X
      public void test()
      {
            A a=new A();
            a.a=12;//Y
            a.b=13;//Y
            a.c=14;//N ||ERROR
            a.d=15;//N ||ERROR C and D are NOT Available and visible
      }
}
package two;

import one.A;
/**********class Y***********/
public class Y {
      public void test()
      {
            A a=new A();
            a.a=12;//Y
            a.b=13;//N ||ERROR
            a.c=14;//N ||ERROR
            a.d=15;//N ||ERROR ONLY a is Available and visible
      }
}

Video Tutorial