- In java access modifiers is the accessibility or scope of a field, method, constructor, or class.
- The access specifiers are used to define how the variables and functions can be accessed outside the class.
- We can change the access level of constructors, fields, methods, and class by applying the access modifier.
- In C++ there are four types of access modifiers, they are:
- Private
- Public
- Protected
- Default
Private
- The private modifier is only within the class and it cannot be accessed from outside the class.
Sample Code
[pastacode lang=”cpp” manual=”class%C2%A0A%7B%C2%A0%C2%A0%0A%0Aprivate%C2%A0int%C2%A0data%3D40%3B%C2%A0%C2%A0%0A%0Aprivate%C2%A0void%C2%A0msg()%7BSystem.out.println(%22Welcome%20to%20Wikitechy%22)%3B%7D%C2%A0%C2%A0%0A%0A%7D%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0%0A%0Apublic%C2%A0class%C2%A0Simple%7B%C2%A0%C2%A0%0A%0A%C2%A0public%C2%A0static%C2%A0void%C2%A0main(String%C2%A0args%5B%5D)%7B%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0%C2%A0A%C2%A0obj%3Dnew%C2%A0A()%3B%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0%C2%A0System.out.println(obj.data)%3B%2F%2FCompile%C2%A0Time%C2%A0Error%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0%C2%A0obj.msg()%3B%2F%2FCompile%C2%A0Time%C2%A0Error%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0%C2%A0%7D%C2%A0%C2%A0%0A%0A%7D%C2%A0%C2%A0″ message=”” highlight=”” provider=”manual”/]
Output

Public
- The public modifier is everywhere, and it can access from within the class, outside the class, within the package and outside the package.
Sample Code
[pastacode lang=”cpp” manual=”package%C2%A0pack%3B%C2%A0%C2%A0%0A%0Apublic%C2%A0class%C2%A0A%7B%C2%A0%C2%A0%0A%0Apublic%C2%A0void%C2%A0msg()%7BSystem.out.println(%22Welcome%20to%20Wikitechy%22)%3B%7D%C2%A0%C2%A0%0A%0A%7D%C2%A0%C2%A0″ message=”” highlight=”” provider=”manual”/]
Output

Protected
- The protected modifier is within the package and outside the package through child class.
- It cannot be accessed from outside the package, if you do not make the child class.
Sample Code
[pastacode lang=”cpp” manual=”package%C2%A0pack%3B%C2%A0%C2%A0%0A%0Apublic%C2%A0class%C2%A0A%7B%C2%A0%C2%A0%0A%0Aprotected%C2%A0void%C2%A0msg()%7B%0ASystem.out.println(%22Welcome%20to%20Wikitechy%22)%3B%0A%7D%C2%A0%C2%A0%0A%0A%7D%C2%A0%C2%A0″ message=”” highlight=”” provider=”manual”/]
Output

Default
- The default modifier is only within the package and it cannot be accessed from outside the package.
- It will be the default, if you do not specify any access level.
Sample Code
[pastacode lang=”cpp” manual=”package%C2%A0pack%3B%C2%A0%C2%A0%0A%0Aclass%C2%A0A%7B%C2%A0%C2%A0%0A%0A%C2%A0%C2%A0void%C2%A0msg()%7BSystem.out.println(%22Welcome%20to%20Wikitechy%22)%3B%7D%C2%A0%C2%A0%0A%0A%7D%C2%A0″ message=”” highlight=”” provider=”manual”/]
Output
