Access limitation or we can say it

Access
Modifiers/Access Specifiers:

 

As we know that encapsulation associate
data with code that manipulates it. Though, encapsulation provides another
important characteristic of “Access Control”. Through encapsulation, we can have
power over parts of a program that can access the members of a class. By
controlling access, we can also put off misuse. 

We Will Write a Custom Essay Specifically
For You For Only $13.90/page!


order now

                     How a member can
be accessed is determined by the “Access Modifier”. Java’s access modifiers are
public, private, protected and default
respectively.

 

Public ACCESS MODIFIER:

 

When
a member of a class is modified or declared as by “Public” then that member of
the class can be accessed by anywhere without any limitation or we can say it
can be modified by any other code. Let’s take an example,

 

Source code:

 

     Public Class:                                                  
Test Class:

 

 

 

 

Output:

 

 

 

 

 

 

 

Private ACCESS MODIFIER:

 

When a member of a class is declared as
“Private”, then that member can only be accessed within the same class and only
members of the same class can access private members of the class. For example,

 

Source code:

 

   
Public Class:                                                         
Test Class:

 

 

Output:

 

Exception in thread
“main” java.lang.RuntimeException: Uncompilable source code –
display() is not public in privateexample.PrivateExample; cannot be accessed
from outside package.

 

Protected ACCESS MODIFIER:

 

Protected
data member and method are only accessible by the classes of the same package
and the subclasses present in any package. The protected access modifier is accessible within package
and outside the package it can only be accessed through inheritance only. For
example,

 

Source code:

 

 Public Class:                                                
Test Class:

 

 

 

 

Output:

 

Default ACCESS MODIFIER:

 

Default
modifier also means using no modifier at all or by default. This kind of
modifier is only accessible within the same package. For
example,

 

Source code:

 

   Public Class:                                                       Test
Class:

 

Output:

 

Error means
that the package protectedexample’s addtwoNumbers method is not visible to the
test class package.

 

run:

Exception
in thread “main” java.lang.RuntimeException: Uncompilable source code
– Erroneous sym type: protectedexample.Addition.display

                                                at
protectedexample.Test.main(Test.java:10)

C:UsersDellAppDataLocalNetBeansCache8.2executor-snippets
un.xml:53:
Java returned: 1

BUILD
FAILED (total time: 1 second)