Friday, 29 January 2016

Access Specifiers in java

In java a number of access specifiers to set access levels of classes, variables, methods and constructors. They are below.

  • default
  • private
  • public
  • protected

1. 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

//save by Sample.java 
package pack;
class Sample{
  void msg(){System.out.println("Hello");}
}  

//save by SampleOne.java  

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

2. private access specifier
The private access modifier is accessible only within class.

Example:
class Sample{
private int a =10;
private void msg(){System.out.println("Hello one");}
}
public class SampleOne{
 public static void main(String args[]){
   Sample obj=new Sample();
   System.out.println(obj.a);//Compile Time Error 
   obj.msg();//Compile Time Error 
   }
}  

3.public access specifier
The public access modifier in java is accessible from everywhere inside the program. 

Example:
//save by One.java 
package example;
public class One{
public void msg(){System.out.println("Hello");}
}  
//save Two.java 
 
package myexample;
import example.*;
class Two{
  public static void main(String args[]){
   One obj = new One();
   obj.msg();
  }
}  

Output:
Hello

4.protected access specifier
Variables, methods and constructors which are declared protected in a superclass can be accessed only by the subclasses in other package or any class within the package of the protected members' class.

Example:
class One{
   protected boolean run(int a) {
      // implementation details
   }
}
//subclass
class Two extends One{
   boolean run(int a) {
      // implementation details
   }
}

No comments :

Post a Comment