Wednesday, 8 January 2014

Access Specifiers

The access specifiers specifies accessibility (scope) of a data member, method, constructor or class.

There are 4 types of access specifiers:
  •     private
  •     default
  •     protected
  •     public


 Private: The private access modifier is accessible only within class.

Example: 
package date;


class Test {
private int number = 10;
private void display() {
System.out.println("Private Demo");
}
}

public class Demo {

/**
* @param args
*/
public static void main(String[] args) {
Test obj = new Test();
System.out.println(obj.number); // error occurs i.e. the field Test.number is not visible.
obj.display(); // error occurs i.e. The method display() from the type Test is not visible.

}

}


 Default: If you don't use any modifier, it is treated as default by default. The default modifier is accessible only within package.
Example:
Class 1: 
package date;


public class Demo {

/**
* @param args
*/
int number = 10;
void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {

}

}

Class 2: 
package test;

import date.Demo;
public class demo {

/**
* @param args
*/
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.number); // The field Demo.number is not visible
obj.display(); //The method display() from the type Demo is not visible
}

}


 Protected: The protected access modifier is accessible within package and outside the package but through inheritance only. The protected access modifier can be applied on the data member, method and constructor. It can't be applied on the class.
Example: 
Class 1: 
package date;


public class Demo {

/**
* @param args
*/
protected int number = 10;
protected void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {

}

}

Class 2: 
package test;

import date.Demo;
public class demo extends Demo{

/**
* @param args
*/
public static void main(String[] args) {
demo obj = new demo();
System.out.println(obj.number);
obj.display();
}

}


 Public: The public access modifier is accessible everywhere. It has the widest scope among all other modifiers.
Example: 
Class 1:
package date;

public class Demo {

/**
* @param args
*/
public int number = 10;
public void display() {
System.out.println("Private Demo");
}
public static void main(String[] args) {

}

}

Class 2: 
package test;

import date.Demo;
public class demo {

/**
* @param args
*/
public static void main(String[] args) {
Demo obj = new Demo();
System.out.println(obj.number);
obj.display();
}

}

No comments:

Post a Comment