Wednesday 9 November 2016

ACCESS QUALIFIERS/VISIBILITY CONTROL



  In certain situations it is necessary to restrict the access to certain variables and methods from outside of class. This can be achieved in Java by using the Visibility Modifiers/Access Modifiers/Access Qualifiers. Java provides three types of access qualifiers: public, private and protected. They provide different level of protections as shown below:
o   Public Access:
§  A variable or method declared as public has the widest possible visibility and accessible everywhere.
§  Ex:public  int number;
public void sum(){…….}
o   Friendly Access:
§  When no access qualifier is specified , the member defaults to a limited version of public accessibility known as “friendly” level of access.
§  Ex: int number;
void sum(){…….}
o   Protedted Access:
§  A variable or method declared as protectedhas the visibility not only to the class and subclasses in the same package but also to subclasses in other packages.
§  Ex:protected int number;
protected void sum(){…….}
o   Private Access:
§  A variable or method declared as privatehas visibility only within the same class.
§  They cannot be inherited and thus are not accessible by the subclasses.
§  It is not possible to override a non-private method in a subclass and then make it private.
§  Ex:private int number;
private void sum(){…….}
o   Private Protected Access:
§  A variable or method declared as private protectedhas the visibility level between private and protected
§  The fields are visible in all subclasses regardless of the package. But the fields are not accessible by other classes of the same package.
§  Ex:private protected int number;
private protected voidsum (){…….}
 Access Modifier

Access Location
public
protected
friendly
(default)
private
protected
private
Same class
Yes
Yes
Yes
Yes
Yes
Subclass in same Package
Yes
Yes
Yes
Yes
No
Other classes in Same Package
Yes
Yes
Yes
No
No
Subclasses in other packages.
Yes
Yes
No
Yes
No
Non-Subclasses in other packages
Yes
No
No
No
No

No comments:
Write comments