Friday, 27 January 2017

ACCESS MODIFIERS IN JAVA

The keywords which define accessibility permission are called Access modifiers.

Different levels of Accessibility permission levels
Java supports 4 accessibility levels –
1. Only within the class
2. Only within the package
3. Outside the package but only in subclass by assigning the same subclass object
4. From all places of project

To define the above 4 levels we have 3 keywords –

1. private Access Modifier – private : Variables, Methods and Constructors that are declared private can only be accessed within the declared class itself. Private access modifier is the most restrictive access level modifier. Class and interfaces cannot be private. Variables that are declared private can be accessed outside the class, if public getter methods are present in the class.

2. protected Access Modifier – protected : Variables, methods and constructors which are declared protected in a super class can be accessed only by the subclass in other package or any class within the package of the protected members class.

3. public Access Modifier – public : A class, method, constructor, an interface etc declared public can be accessed from any other class. Therefore fields, methods, blocks declared inside a public class can be accessed from any class belonging to the java universe. However if the public class we are trying to access in a different package, then the public class still needs to be imported. Because of class inheritance, all public methods and variables of a class are inherited by its subclass.

4. Default Access Modifier – Not a keyword : default access modifier means that explicitly an access modifier for a class, field, method, etc is not declared. A variable or method declared without any access modifier is available to any other class in the same package. The fields in an interface are implicitly public static final and the methods in an interface are by default public.

Example -
class Modi1 {
          private int a=10;
          int b=20;
          protected int c=30;
          public int d=40;
          public static void main(String[] args) {
                   Modi1 m = new Modi1();
                   System.out.println(m.a);
                   System.out.println(m.b);
                   System.out.println(m.c);
                   System.out.println(m.d);
          }
}

Output –
10
20
30
40

The above program is compiled and executed without errors, but non-private members are accessible outside the class. If we access private members outside class members, compiler throws CE.

Example –
class Modi2 {
          public static void main(String[] args) {
                   Modi1 m = new Modi1();
                   System.out.println(m.a);
                   System.out.println(m.b);
                   System.out.println(m.c);
                   System.out.println(m.d);
          }

}

No comments:

Post a Comment