VISIBILITY CONTROL IN JAVA
ACCESS MODIFIERS
Visibility modifiers also known as access modifiers can be applied to the instance variables and methods within a class.
Java provides the following access modifiers
Public
Friendly/Package (default)
Private
Protected
PUBLIC ACCESS
Any variable or method is visible to the entire class in which it is defined.
What is we want to make it visible to all classes outside the current class??
This is possible by simply declaring the variable as ‘public’
When no access modifier member defaults to a limited version of public accessibility known as ‘friendly’ level of access. This is also known as package access.
FRIENDLY ACCESS
So what is the difference between the public and the friendly access???
The difference between the public and the friendly access is that public modifier makes the field visible in all classes regardless of their package while the friendly access make them visible only within the current package and not within the other packages.
PROTECTED ACCESS
The visibility level of the protected field lies between the private and the package access.
That is the protected access makes the field visible not only to all classes and subclasses in the same package but also to subclasses in other package
Non subclasses in their packages cannot access the protected members
Enjoys high degree of protection. They are accessible only within their own class They cannot be inherited by their subclass and hence not
visible in it.
PRIVATE ACCESS
Public Protected Friendly Private
Same class Yes Yes Yes Yes
Subclass in same package Yes Yes Yes No
Other classes in same package Yes Yes Yes No
Subclasses in other package Yes Yes No No
Non subclasses in other package Yes No No No
AccessModifier
AccessLocation