blog

Home / DeveloperSection / Blogs / Visibility Modes and Access Modifiers in Java

Visibility Modes and Access Modifiers in Java

Simond Gear12403 17-May-2016

We know java uses four access modifiers public, protected, default and private to maintain visibility at various levels. Let’s discuss how to define this visibility. Four possible values control the visibility or the access level of the entities in your program:

1.   private: If an entity is declared with a private modifier, it will be accessible only to the code that is contained within the class that defines the entity.

2.  protected:The entity can only be accessed by code that is contained

a.    within the class that defines the entity,

b.    by classes within the same package as the defining class,

c.    or by a subclass of the defining class, regardless of the package in which the subclass is declared.


3.    default (or package): The entity can be accessed by code that is contained

a.  within the class that defines the entity

b.  or by a class that is contained in the same package as the class that defines the entity.

4.   public: The entity can be accessed by code in any class. 

These visibility modes are specified with specific keywords: public, protected, and private. If any of these keywords are not used as qualifiers, the entity is given a default visibility (that is, package-private or friendly). The four access modifiers and the resulting corresponding visibility are summarized in table below.

Note that there is no modifier called “default” If we do not specify any of the modifiers explicitly, the default is assumed. To understand these accessibility rules, we must first understand the levels at which this visibility is tested.

Accessibility is decided at five different levels:

·   Same class: Check whether the element is accessible to the code defined within the same class where the element is declared.

·   Same package subclass: The classes are grouped together in a package. We test the visibility for access within a subclass declared in the same package.

·   Same package non-subclass: We test the visibility within a class that belongs to the same package but does not inherit from the declaring class.

·   Different package subclass: We test the visibility within a class that inherits from a class belonging to a different package.

·   Different package non-subclass: In this case, the class neither derives from the declaring class nor belongs to the same package as the declaring class.

 

 

 

Same Packages

Different Packages

Modifers

Same Class

Sub Class

Nonsub Class

Sub Class

Nonsub Class

public

Yes

Yes

Yes

Yes

Yes

private

Yes

No

No

No

No

protected

Yes

Yes

Yes

Yes

No

Default

Yes

Yes

Yes

No

No

 


Updated 14-Mar-2018

Leave Comment

Comments

Liked By