Protected vs Package Access Modifiers in Java
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.
GFG GFG GFG
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.
Finally, after getting it done with both o them let us conclude the evident differences between them
|Package access modifier||Protected access modifier|
|This modifier is applicable to both top-level classes and interface||This modifier is not applicable to both top-level classes and interface|
|We cannot access this modifier from the child class of the outside package.||We can access this modifier from the child class of the outside package, but we should use child reference only.|
|This modifier is more restricted than the protected modifier.||This modifier is more accessible than the package level modifier.|
Please Login to comment...