One of the prime features of object oriented programming is data encapsulation.This feature enables data to have restricted access.There are currently four different access specifiers in JAVA. Namely,
Public:- All the data members and member functions which are declared public can be accessed from anywhere outside or inside the class which means it can be accessed by any object or through any member functions.It is also called a class level access modifier as class is usually made public in JAVA so that it can be accessed from anywhere.
Private:- All the data members and member functions which are declared as private can be accessed only from that specific class where it belongs. It cannot be accessed from anywhere else outside that class whether it is an object,function or a class. Thus private methods and fields cannot be inherited by any subclass and thus cannot be accessed by any sub-class.
Protected:- Any data member,member functions which are declared as protected can be accessed from within that class and any subclass of that specific class to which they belong whether it is in the same package or different package. The access level remains unchanged while inheritance from one class to the other in JAVA.
Default( No specifier):- Any data member,member functions which has no access specifier mentioned to it , it can be accessed from within that package where the class,method or field belongs but not from anywhere outside that package. Sometimes there are no access levels mentioned to a class and this is when the class can be accessed from anywhere within the same package only.
Following is the tabular representation for Java access specifiers
- Public
- Protected
- Default
- Private
Public:- All the data members and member functions which are declared public can be accessed from anywhere outside or inside the class which means it can be accessed by any object or through any member functions.It is also called a class level access modifier as class is usually made public in JAVA so that it can be accessed from anywhere.
Code:
public class A{ //public class
public a; //public variable declaration
public call( ); //public method declaration
}
Protected:- Any data member,member functions which are declared as protected can be accessed from within that class and any subclass of that specific class to which they belong whether it is in the same package or different package. The access level remains unchanged while inheritance from one class to the other in JAVA.
Default( No specifier):- Any data member,member functions which has no access specifier mentioned to it , it can be accessed from within that package where the class,method or field belongs but not from anywhere outside that package. Sometimes there are no access levels mentioned to a class and this is when the class can be accessed from anywhere within the same package only.
Following is the tabular representation for Java access specifiers
