Explain different levels of access modifier available in java for protection.
https://www.computersprofessor.com/2016/06/explain-different-levels-of-access.html
It is possible to inherit
all the members of a class by a subclass using the keyword extends. However,
it may be necessary in some situations to restrict the access to certain
variables and methods from outside the class. For example, we may not like
the objects of a class directly alter the value of a variable or access a
method. We can achieve this in java by applying visibility modifiers. Java
provides three types of visibility modifiers: public, private and protected.
They provide different levels of protection as described bellow.
|
Public
Access:-
Any variable or method is visible to the entire class in which it is defined.
This is possible by simply declaring the variable or method as public.
Example :- Public int number ;
Public
void sum() {…………}
|
A variable or method
declared as public has the widest possible visibility and accessible
everywhere. In fact, this is what we would like to prevent in many programs.
This takes us to the next levels of protection.
|
Friendly
Access:-
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. Note that non – subclasses in other packages
can’t access the “protected” members.
|
Private
Access:-
Private fields enjoy the highest degree of protection. They are accessible
only within their own class. They can’t be inherited by subclasses and
therefore not accessible in subclasses. A method declared as private behaves like
a method declared as final. It prevents the method from being sub classed.
Also note that we can’t override a non – private method in a subclass and
then make it private.
|
Private protected
Access:-
A field can be declared with two keywords private and protected
together like:
Private protected int
code number ;
|
This gives a visibility
level in between the protected access and private access. This modifier makes
the fields visible in all subclass regardless of what package they are in.
Remember, these fields are not accessible by other classes in the same
package.
|