![]() |
Whenever we are writing our classes, we have to provide some information about our classes to the JVM like whether this class can be accessed from anywhere or not, whether child class creation is possible or not, whether object creation is possible or not, etc. we can specify this information by using an appropriate keyword in java called access modifiers. So access modifiers are used to set accessibility of classes, methods, and other members. Modifier 1: Protected Access Modifier This modifier can be applied to the data member, method, and constructor, but this modifier can’t be applied to the top-level classes and interface. A member is declared as protected as we can access that member only within the current package but only in the child class of the outside package. Example: Java
Output
GFG GFG GFG Output explanation: In the above example, we create three objects using parent reference and child reference and call m1() method on it, and it successfully executed so from the above example we can say that we can access the protected method within the current package anywhere either by using parent reference or by child reference. Modifier 2: Package(Default) Access Modifier A class or method or variable declare without any access modifier then is considered that it has a package(default)access modifier The default modifier act as public within the same package and acts as private outside the package. If a class is declared as default then we can access that class only within the current package i.e from the outside package we can’t access it. Hence, the default access modifier is also known as the package–level access modifier. A similar rule also applies for variables and methods in java. Example: Java
Output
GeeksforGeeks Finally, after getting it done with both o them let us conclude the evident differences between them
|
Reffered: https://www.geeksforgeeks.org
Difference Between |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |