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.
Lets us discuss both of the modifiers in-depth individually
- Package(Default) Access Modifier
- Private Access Modifier
Modifier 1: 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.
Modifier 2: Private Access Modifier
This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructors, methods, and fields inside the classes. If a variable or methods or constructor is declared as private as we can access them only from within the class i.e from outside the class we can’t access them.
Finally, after getting it done with both of them let us conclude the evident differences between them which are as follows:
Package Access Modifier Private Access Modifier This modifier is applicable for both top-level classes and interfaces. This modifier is not applicable for both top-level classes and interfaces. Package members can be accessed from the child class of the same package. Private members cannot be accessed from the child class of the same package. Package members can be accessed from a non-child class of the same package. Private members cannot be accessed from a non-child class of the same package. The package modifier is more accessible than the private modifier. The private modifier is more restricted than a package modifier. Package modifier provides the lowest level of Encapsulation in java. A private modifier provides a higher level of Encapsulation in Java.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.