Access Modifiers in Java

Profile picture for user arilio666

Need security? Restrict accessibility? In Java, we have access modifiers that helps us to restrict the class scope, constructor, variable, method, or data member. In this article, we will see the types of access modifiers and what they do.

There are four types of access modifiers:

  1. Private
  2. Protected
  3. Default 
  4. Public

Default

Members declared without any access modifier are only accessible within the same package.

class classname {
   int var; // default variable
   void method() { // default method
   }
}

Private

Members declared as private are only accessible within the same class. They cannot be accessed from other classes or packages.

private class classname {
   private int var; // private variable
   private void method() { // private method
   }
}

Protected

Members declared as protected are accessible within the same package and subclasses (both within and outside the package).

package bob; 
 
public class X 
{ 
protected void display() 
   { 
       System.out.println("John"); 
   } 
}
package Tom; 
import BOB.*; // importing all classes in package BOB 
 
class Y extends X 
{ 
public static void main(String args[]) 
{ 
   Y obj = new Y(); 
   obj.display(); 
} 
     
}

Output:

John

Public

Members declared as public are accessible from any part of the code, including other packages.

public class classname {
   public int var; // public variable
   public void method() { // public method
   }
}

It's crucial to use access modifiers appropriately to control the visibility and accessibility of class members in your Java code to enforce encapsulation and maintain code integrity.

Tags