Access specifier is a mechanism which restricts user to access the data to different classes. Java provides three types of access specifier.
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 |
Leave Comment
1 Comments