Home > DeveloperSection > Articles > Access Specifier in java

Access Specifier in java


Java Java 
Ratings:
1 Comment(s)
 5937  View(s)
Rate this:

Access Specifier in java

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


Re:Access Specifier in java

By Arun Singh on   5 years ago
this is great stuff !!!! thanks for sharing with us.

Don't want to miss updates? Please click the below button!

Follow MindStick