This document discusses visibility and access modifiers in Java. It describes the four access modifiers in Java - public, friendly/package, protected, and private. Public access makes a variable or method visible to all classes, friendly access limits visibility to the current package, protected access extends visibility to subclasses in the same and other packages, and private restricts visibility only to the class defining it. The document provides examples of when each access modifier would be used and summarizes their visibility scopes.
2. 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
3. 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’
FRIENDLY ACCESS
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.
4. 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.
5. 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
PRIVATE ACCESS
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.
6. Access
Modifier
Public Protected Friendly Private
Access
Location
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