What is the difference between public, protected, and private in Java?

In this tutorial, we will learn What is the difference between public, protected, and private in Java? as all these are access modifier that decides the accessibility i different situations and conditions where we can use them all are defined used there access modifiers.

What are Access Modifiers?

public, protected, and private in Java

 

Access Modifiers are the keywords that limit the use of variables or function outside the scope they are declared, They are somewhat similar of globel and local variables, But so much different.

All four keywords have a specific range of access from where the values of it can be accessed so we will learn in by one about all the access modifiers and draw the inference out of these how they are different from global and local variables.

Public

It is a keyword which has the widest range of access as the variable which has an access modifier as the public can be accessed from any location of the program and the value of that variable can be used from anywhere so let’s check which an example and understand more about it.

As in the image above we can see the variable or function which have an access modifier as the public can be accessed from the same class, PAchage, and Subclass and we can say it is what we call a global variable which can be used anywhere in a program.

In either words we can say if want to access any variable from any location in a program then we can use the keyword as public before that variable or function and you are all set to use it anywhere in the program.

Protected

Protected also have a very wide range of access but somewhat less than public as public can be used as globally but protected can not otherwise we can use protected also in class, Package, and even in subclass also. which means it has a limit for access to the public.

But we can say we can make our variable protected if we do not what to use the variable or function outside the package. As it has the rage of access anywhere inside a package.

Private

Private is a keyword that we can also call as local variable as we can not use this variable or function outside the class. So we can say it has the least range of access.

We use a protected access modifier only when we do not need to use the variable anywhere outside of that class and are only useful in the same class. Not even in driver classes.

 

Learn More about Access modifiers and What is the difference between public, protected, and private in Java? at : difference between public Private and protected keys.

And visit JAVA TUTORIALFor learn more about java.

Leave a Comment

%d bloggers like this: