The private access modifier is an access modifier that can be used for classes, fields, methods, and constructors. The private access modifier is the most restrictive. Private members can only be accessed within the same class.
class PrivateModifierExample {// fieldsprivate int field1;// constructorprivate ClassName() {// body of constructor}// methodsprivate void method1() {// body of method}}
Line 1: We have a class called PrivateModifierExample
.
Line 3: This class has a field called field
which is a private member, and can only be accessed within the class.
Line 11: This class has a method called method
which is a private member, and can only be accessed within the class.
Note: Remember to also use the private access modifier on static fields and methods. When you do this, the members can only be accessed within the same class.
The main disadvantage of using the private access modifier is that it cannot be accessed from outside the class.