Access specifiers in java are provided to achieve one of
the OOP concept of Encapsulation.
Use of access specifiers helps in data hiding and making
the system less prone to issues of accidental changes in data.
Access specifiers
in java are defined for Classes, methods and variables.there are four types of
access specifiers available:
1.
Public
2.
Protected
3.
Default(no
specifier)
4.
Private
1.
Public
:
This access specifier is the
most open one.
The variables, methods, constructors, classes or interffaces defined
as public can be accessed from anywhere in Java world.
Note :
a.
While accessing public class in other package,
it needs to be imported first.
b.
The derrived classes autmatically get access to
public members of the base class.
Example :
The main() method defined in
java to be called to start any application is made public so that java
interpreter can access it.
Variable declaration:
Public Integer iAccess;
Method declaration:
Public void method()
{
System.out.println(“ example for protected ”);
}
2.
Protected:
This access specifier is a
super set of “Default” access with access in package and to all subclassess of
the base class in which the protected variable/method is declared.
Note:
a.
Protected is applicable only to variables, constructors
and methods, cannot be used for class/interface.
b.
The protected variables can be accessed in
derrived class only directly, cannot be called with the reference of the base class.
For example : a variable
protected integer a can be accessed in the other package derrived class System.out.println(a) - legal
Base base = new base();
Base.a -- illegal
Example:
Variable declaration:
Protected String sAccess = “Access Specifier”;
Method declaration:
Integer add(int a, int b)
{
return((Integer)(a+b));
}
3.
Default (No Specifier) :
When no specifier is assigned to any method, constructor, class or variable, it is considered to be as
default. The method/variable can be accessed from any class in the same
package. It is also called as “package level” access.
Example :
Variable declaration :
String sAccess = “Access
Specifier”;
Method declaration:
Integer add(int a, int b)
{
return((Integer)(a+b));
}
4.
Private
:
Private access specifier is to
scope a variable, constructor or method to the particular class in which it is
declared/defined. It is the most restricted access level. It is the main way of
obtatining encasulation in java.
Note:
a.
Classess/Interfaces cannot be declared private.
b.
Priavte variables can be accesed from outside
class through public getter methods present in the class.
Example:
Variable declaration :
Private String sAccess =
“Access Specifier”;
Method declaration :
Private Integer add(int
a, int b)
{
return((Integer)(a+b));
}
Above concepts can be put in table as below
Modifier | Class | Package | Subclass | World |
public | Y | Y | Y | Y |
protected | Y | Y | Y | N |
default | Y | Y | N | N |
private | Y | N | N | N |
No comments:
Post a Comment