Java Private Access Modifiers

www.i‮‬giftidea.com

In Java, the private access modifier is used to specify that a class member (field or method) can only be accessed within the same class in which it is declared. The private modifier has the following characteristics:

  • A private field or method can only be accessed within the same class where it is declared, and not from any other class or subclass.
  • A private field or method is not visible to any other class or interface, even if they are in the same package as the class that declares it.

To use the private access modifier in Java, you can declare the field or method with the keyword private like this:

class MyClass {
    private int myPrivateField;
    
    private void myPrivateMethod() {
        // method body
    }
    
    public void myPublicMethod() {
        myPrivateField = 10;  // can access the private field from within the class
        myPrivateMethod();    // can call the private method from within the class
    }
}

In the example above, the myPrivateField and myPrivateMethod are declared as private and can only be accessed within the MyClass class. The myPublicMethod is a public method that can be accessed from outside the class and can access the private fields and methods from within the class.