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’

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.

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

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.

Access Modifier Access Location Same class

Public

Protected

Friendly

Private

Yes

Yes

Yes

Yes

Subclass in same package
Other classes in same package Subclasses in other package

Yes

Yes

Yes

No

Yes

Yes

Yes

No

Yes

Yes

No

No

Non subclasses in other package

Yes

No

No

No

Sign up to vote on this title
UsefulNot useful