AccessModifiers/Access Specifiers: As we know that encapsulation associatedata with code that manipulates it. Though, encapsulation provides anotherimportant characteristic of “Access Control”. Through encapsulation, we can havepower over parts of a program that can access the members of a class. Bycontrolling access, we can also put off misuse.                      How a member canbe accessed is determined by the “Access Modifier”. Java’s access modifiers arepublic, private, protected and defaultrespectively.

 Public ACCESS MODIFIER: Whena member of a class is modified or declared as by “Public” then that member ofthe class can be accessed by anywhere without any limitation or we can say itcan 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 onlymembers 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 accessedfrom outside package. Protected ACCESS MODIFIER: Protecteddata member and method are only accessible by the classes of the same packageand the subclasses present in any package.

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

order now

The protected access modifier is accessible within packageand outside the package it can only be accessed through inheritance only. Forexample, Source code:  Public Class:                                                Test Class:      Output:  Default ACCESS MODIFIER: Defaultmodifier also means using no modifier at all or by default. This kind ofmodifier is only accessible within the same package. Forexample, Source code:    Public Class:                                                       TestClass:   Output: Error meansthat the package protectedexample’s addtwoNumbers method is not visible to thetest class package. run:Exceptionin thread “main” java.lang.RuntimeException: Uncompilable source code- Erroneous sym type: protectedexample.Addition.display                                                atprotectedexample.Test.main( returned: 1BUILDFAILED (total time: 1 second)