DEV Community

loading...
Cover image for Java Concept of the Day.

Java Concept of the Day.

the_unconventional_coder profile image ABHINAVA GHOSH (he/him) Updated on ・2 min read

This is the continuation of the post where i will be discussing one core java concept every alternate day.

ORIGINAL POST

Today's concept-Java Access Modifiers.

Java ,unlike many other OOP language has 4 access modifiers.
public
protected
default
private

public: The access level of a public modifier is everywhere. It can be accessed from within the class, outside the class, within the package and outside the package.

protected : The access level of a protected modifier is within the package and outside the package through child class. If you do not make the child class, it cannot be accessed from outside the package.

default: the access level of a default modifier is only within the package. It cannot be accessed from outside the package. If you do not specify any access level, it will be the default.

private : The access level of a private modifier is only within the class. It cannot be accessed from outside the class.

The Access modifiers below are arranged in decreasing order of visibility:

public>protected>default>private

Access Modifiers on Classes:

For outer classes there is only two choices: public,default
For inner classes there is no restriction,all four can be used.

NOTE:each java file can only contain one public class,and the name of that public class has to be same as of the file name.

Access Modifiers on Member Variables and Functions:

Public data members:they are accessible for any class in any package.(No security)

Protected data members:they can be accessed from classes of the same package and also from classes of other packages who inherit them,in other words, if any class from any other package is a child class then that class can access protected data members through inheritance.

Default data members:the other name for default is package private.Thus default data members are accessible only from the same package.

Private data members:Only accessible from the class in which they are declared(Most Secure).

NOTE: If we are overriding any method, overridden method (i.e. declared in subclass) must not be more restrictive.

What this means is that while overriding the accessibility can only be increased (or the same as parent class) ,but cannot be decreased.

Thus:
public cannot be changed to private,default,protected.
protected cannot be changed to private,default
default cannot be changed to private
Methods declared private are not inherited at all, so there is no rule for them.

oracle java documentation

Please like this post if it helped you , liking this article will provide motivation for me to deliver even better articles in the future.

Thank You for taking out the time to read this article.
Please comment down any suggestions for me .
And let me know what topic i should cover next.

Discussion (0)

pic
Editor guide