Whenever we are writing our classes we have to provide some information about our classes to the JVM like whether this class can be accessible 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.
Public Access Modifiers :
If a class is declared as public then we can access that class from anywhere.
In the below example we are creating a package pack1 inside that package we declare a class A which is public and inside that class, we declare a method m1 which is also public. Now we create another package pack2 and inside that pack2 we import pack1 and declare a class B and in class B main method we create an object of type class A and trying to access the data of method m1.
If class A is not public while compiling B class we will get compile-time error saying pack1. A is not public in pack1 and can’t be accessed from the outside package.
Similarly, if a member or method or interface is declared as public then we can access that member from anywhere.
Private Access Modifiers:
This modifier is not applicable for top-level classes or interfaces. It is only applicable to constructor, methods, and fields inside the classes.
If a variable or methods or constructor is declared as private then we can access them only from within the class i.e from outside the class we can’t access them.
|Public 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.|
|Public 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.|
|Public member can be accessed from non-child class of same package.||Private members cannot be accessed from non-child class of same package.|
|Public members can be accessed from child class of outside package.||Private members cannot be accessed from child class of outside package.|
|Public members can be accessed from non-child class of outside package.||Private members cannot be accessed from non-child class of outside package.|
|Public modifier is the most accessible modifier.||Private modifier is the most restricted modifier.|
|Public modifier is the recommended modifier for method.||Private modifier is the recommended modifier for data members.|
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.