/* related posts with thumb nails */

Visibility control (visibility access) in Java (or) Access modifiers:

It is possible to inherit all the members of a class by a subclass using the keyword extends. The variables and methods of a class are visible everywhere in the program. However, it may be necessary in some situations we may want them to be not accessible outside. We can achieve this in Java by applying visibility modifiers to instance variables and methods. The visibility modifiers are also known as access modifiers. Access modifiers determine the accessibility of the members of a class.

Java provides three types of visibility modifiers: public, private and protected. They provide different levels of protection as described below.

Public Access: Any variable or method is visible to the entire class in which it is defined. But, to make a member accessible outside with objects, we simply declare the variable or method as public. A variable or method declared as public has the widest possible visibility and accessible everywhere.

Friendly Access (Default): When no access modifier is specified, the member defaults to a limited version of public accessibility known as "friendly" level of access. The difference between the "public" access and the "friendly" access is that the public modifier makes fields visible in all classes, regardless of their packages while the friendly access makes fields visible only in the same package, but not in other packages.

Protected Access: The visibility level of a "protected" field lies in between the public access and friendly access. That is, the protected modifier makes the fields visible not only to all classes and subclasses in the same package but also to subclasses in other packages

Private Access: private fields have the highest degree of protection. They are accessible only with their own class. They cannot be inherited by subclasses and therefore not accessible in subclasses. In the case of overriding public methods cannot be redefined as private type.

Private protected Access: A field can be declared with two keywords private and protected together. This gives a visibility level in between the "protected" access and "private" access. This modifier makes the fields visible in all subclasses regardless of what package they are in. Remember, these fields are not accessible by other classes in the same package.

The following table summarises the visibility provided by various access modifiers.

Access modifier à

public

protected

friendly

private protected

private

Own class

ü

ü

ü

ü

ü

Sub class

in same package

ü

ü

ü

ü

û

Other classes

In same package

ü

ü

ü

û

û

Sub class

in other package

ü

ü

û

ü

û

Other classes

In other package

ü

û

û

û

û


Related Topics:

1 comments:

Sridevi Chelimela said...

I need a program on ds topic

Post a Comment