Access specifier is a mechanism which restricts user to access the data to different classes. Java provides three types of access specifier.
Public: It is keyword in java used in a method or variable declaration. It signifies that the method or variable can be accessed by elements residing in other classes also.
Private: It is keyword in java used in a method or variable declaration. It signifies that the method or variable can be accessed by other elements of its class.
Protected: It is keyword in java used in a method or variable declaration. It signifies that the method or variable can be accessed by elements residing in its class, subclasses, or classes in the same package.
Note: Default access specifier in java is public.
Example:
Here is simple demonstration how to use the access specifier in java?.class Base
{
private int x;
protected int y;
public int z;
Base()
{
x=10;
y=20;
z=30;
}
void show()
{
System.out.println(x);
System.out.println(y);
System.out.println(z);
}
}
class Derived extends Base
{
public int a;
private int b;
protected int c;
Derived()
{
a=40;
b=50;
c=60;
}
void show()
{
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
public static void main(String args[])
{
Derived d=new Derived();
d.show();
System.out.println(x);
System.out.println(y);
System.out.println(a);
System.out.println(b);
System.out.println(c);
}
}
This chart show the area where allow the access specifier.
Access Specifier | Base Class | Derived Class | Outside Class |
Private | True | False | False |
Protected | True | True | False |
Public | True | True | True |
Anonymous User
08-Oct-2011