Saturday, 18 July 2015

Access Modifiers in java

Understanding all java access modifiers:
                                                                       


There are two types of modifiers in java: access modifiers and non-access modifiers.

Access modifiers in java are used to control the visibility of a field, method, class and contrustor. There are 4 access modifiers in java. They are : 1). Private   2). Default or Package  3). Protected  4). Public

Non-access modifiers are static, abstract, final, synchronized, native, volatile, transient, strictfp.

1). Private Access Modifier

Private members of a class whether it is a field or method or constructor can not be accessed outside the class.

Inheritance of Private Members :

Private members will not be inherited to sub class.

Important Note :

1). Class can not be a private except inner classes. Inner classes are nothing but again members of outer class. So members of a class (field, method, constructor and inner class) can be private but not the class itself.

2). We can’t create sub classes to that class which has only private constructors.

class A
{
    private int i;

    private void methodOfClassA()
    {
        System.out.println(i);   //Private field can be used within class
        B b = new B();               //Private inner class can be used within class
    }

    private class B
    {
      //Private Inner Class
    }
}

class C extends A
{
    void methodOfClassC()
    {
        //System.out.println(i);       Private member can not be inherited
        A a = new A();
        //System.out.println(a.i);     Private field can not be used outside the class
        //a.methodOfClassA();          Private method can not be used outside the class
        //A.B b = new A.B();           Private inner class can not be used outside the class
    }
}


2)Default Access Modifier

If you don't use any modifier, it is treated as default bydefault. The default modifier is accessible only within package.

Example of default access modifier

In this example, we have created two packages pack and mypack. We are accessing the A class from outside its package, since A class is not public, so it cannot be accessed from outside the package.

package pack;  
class A{  
  void msg(){System.out.println("Hello");}  
}  

package mypack;  
import pack.*;  
class B{  
  public static void main(String args[]){  
   A obj = new A();   //Compile Time Error  
   obj.msg();              //Compile Time Error  
  }  
}  


In the above example, the scope of class A and its method msg() is default so it cannot be accessed from outside the package.

3). Protected Access Modifier

Protected member can be used within the package only.

Inheritance Of Protected Member :

Protected Member can be inherited to any sub classes.

package pack1;

public class A
{
    protected int i;

    protected void methodOfClassA()
    {
        System.out.println(i);  //Protected field can be used within class
        B b = new B();              //Protected Inner Class can be used within class.
    }

    protected class B
    {
      //Protected Inner Class
    }
}

class C extends A
{
    void methodOfClassC()
    {
        System.out.println(i);        //Protected field can be inherited to any sub class 
        A a = new A();
        System.out.println(a.i);     //Protected field can be used within the package
        a.methodOfClassA();          //Protected method can be used within the package
        A.B b = new A.B();           //Protected Inner Class can be used within the package
    }
}

package pack2;
import pack1.A;  

class D extends A
{
    void methodOfClassD()
    {
        System.out.println(i);        //Protected field can be inherited to any sub class 
        A a = new A();
        //System.out.println(a.i);     Protected field can not be used outside the package
        //a.methodOfClassA();          Protected method can not be used outside the package
        //A.B b = new A.B();           Protected inner class can not be used outside the package
    }
}

Important Note :

1). Outer class can not be protected.


2). We can create sub classes to a class which has only protected constructors but we can’t create objects to that class outside the package.


4) Public Access Modifier

The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
  
package pack;  
public class A{  
public void msg(){System.out.println("Hello");}  
}  
  
package mypack;  
import pack.*;  
  
class B{  
  public static void main(String args[]){  
   A obj = new A();  
   obj.msg();  
  }  

}  

Java access modifiers with method overriding:

If you are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

class A{  
protected void msg(){System.out.println("Hello java");}  
}  
  
public class Simple extends A{  
void msg(){System.out.println("Hello java");}   //Compile Time Error  
 public static void main(String args[]){  
   Simple obj=new Simple();  
   obj.msg();  
   }  
}  

Non-Access Modifiers In Java :

Java provides some other modifiers to provide the functionalities other than the visibility. These modifiers are called Non-Access Modifiers. There are many non-access modifiers available in java. Each modifier have their own functionality. Some of the most used non-access modifiers are listed below.

1) static : The members which are declared as static are common to all instances of a class. Static members are class level members which are stored in the class memory. Click here for more info on static members.

2) final : This modifier is used to restrict the further modification of a variable or a method or a class. The value of a variable which is declared as final can’t be modified once it gets a value. A final method can not be overridden in the sub class and you can not create a sub class to a final class. See this post for more info on final keyword in java.

3) abstract : This modifier can be used either with a class or with a method. You can not apply this modifier to variable and constructor. A method which is declared as abstract must be modified in the sub class. You can’t instantiate a class which is declared as abstract. See this post for more info on abstraction in java.

4) synchronized : This modifier is used to control the access of a particular method or a block by multiple threads. Only one thread can enter into a method or a block which is declared as synchronized. Click here for more info on synchronization in java.

5) transient : This modifier is used in serialization process. A variable which is declared as transient will not be serialized during object serialization.

6) volatile : volatile modifier is used in multi threaded programming. If you declare a field as volatile it will be signal to the threads that it’s value must be read from the main memory rather then their own stack. Because volatile field is common to all threads and it will be updated frequently by multiple threads.


7) strictfp : This modifier is used for floating-point calculations. This keyword ensures that you will get same floating point presentation on every platform. This modifier makes floating point variable more consistent across multiple platforms.