refresh java logo

Access Modifiers in Java

Access modifiers, as the name itself suggests, are used to control the accessibility/visibility of variables, methods, constructors of a class inside another class. Java provides some keywords to accomplish the same, these keywords are known as access modifiers. These modifiers decides whether other classes can use a particular variable, method, constructor of a class or not. There are four types of access modifiers in java.

  • Private (declared using private keyword)
  • Default or package private (when no keyword is used)
  • Protected (declared using protected keyword)
  • Public (declared using public keyword)

All these modifiers can be used with variables, constructors and methods of a class while Default and Public access modifiers can also be used with top level classes and interfaces. To understand this tutorial easily, you must have knowledge about packages in java, if not refer the packages tutorial first.

An access modifier must be used before the data type of a variable and return type of a method. In case of class, interface or enum it must be used before the class, interface and enum keyword. Some of the examples of using access modifiers with different members are :

  private int count = 0; // Correct 
  public String print() {  } // Correct
  public class MyClass {  } // Correct
  int protected id = 20; // Wrong 
  void public getDetail() {  } // Wrong 

Private Access Modifier

A member is declared private using private keyword. This is the most restrictive access modifier in java. The code below declares the variable count as private.

  private int count = 0;      

. Some key points about private access modifier are :

  • A private member is accessible within it's own class only. For example a variable count defined as private, inside class A will be accessible within class A only, no other classes can access this variable.
  • Variables, methods and constructors can be declared as private.
  • Top level classes and interfaces can not be declared as private, where as nested classes and interfaces can be declared as private.
  • If a class has private constructor then we cannot create the object of that class in another class.

Java Program of private modifier

 class PrivateModifier {                           
       private int count = 10;      
       private void printMessage() {
            System.out.println("count = : "+count);
        }                 
   }
      
 class PrivateModifierTest {
     private int num = 20;
     
     public static void main(String [] args) {
         PrivateModifierTest pmt = new PrivateModifierTest();
         pmt.printDetail();
         System.out.println("num = "+pmt.num);
         PrivateModifier pm = new PrivateModifier();  
         // pm.printMessage(); // compilation error                           
         // System.out.println(pm.count); // compilation error
       }
     private void printDetail() {
         System.out.println("Private modifier program");
      }
   }

Output:

Private modifier program
num = 20

As you can see in above program class PrivateModifierTest is able to access it's private variable and method but if you uncomment last two line in PrivateModifierTest class it will result in compilation error as it can not access private members of PrivateModifier class.

Default Access Modifier

When a member is declared without any access modifier, it is called default modifier. So default is not a keyword, it's just when we don't use any access modifier, it is called default or no modifier. It is also known as package-private access modifier. The code below declares the variable count as default.

 int count = 0;      

Some key points about default access modifier are :

  • A default member is accessible within the package only, that is why it is also known as package-private modifier. For example a variable count defined with no modifier inside class A can be accessed by a class B if class B is in same package as class A.
  • Any member can be declared with no modifier whether it's a variable, method, constructor, class, interface or anything else.
  • Nested classes and interfaces can also be declared with no modifier.

Java Program of default modifier

 package mypack;
 
 class DefaultModifier {                           
    int count = 10;
    void printMessage() {
         System.out.println("Default modifier program");
      }                 
   }
      
 public class DefaultModifierTest {
     public static void main(String [] args) {                
        DefaultModifier dmf = new DefaultModifier();  
        dmf.printMessage();                           
        System.out.println("count = "+dmf.count);       
      }
  }

Output:

Default modifier program
count = 10

As you can see in above program class DefaultModifierTest is able to access the default variable and method of class DefaultModifier, since both classes are in same package mypack. If both classes were in different packages, this program would have resulted in compilation error.

Protected Access Modifier

A member is declared protected using protected keyword. Code below declares the variable count as protected.

  protected int count = 0;      

Some key points about protected modifier are :

  • A protected member can be accessed within it's own package as well as by a subclass in another package. For example a variable count defined with protected modifier inside class A can be accessed by class B if class B is in same package as class A or class B is in different package but it's a subclass of class A.
  • This access modifier can be used with variable, method and constructors.
  • Top level classes and interfaces can not be declared as protected, where as nested classes and interfaces can be declared as protected.

Java Program of protected modifier

 package testpack;
 
 public class ProtectedModifier {                           
     protected int count = 10;
     protected void printMessage() {
     System.out.println("Protected modifier program");
   }                 
 }
 package mypack; 
 import testpack.ProtectedModifier;
      
 public class ProtectedModifierTest extends ProtectedModifier {
     public static void main(String [] args) {                
        ProtectedModifierTest pmf = new ProtectedModifierTest();                              
        pmf.printMessage();
        System.out.println("count = "+pmf.count);
     }
 }

Output:

Protected modifier program
count = 10

Here both classes are in different packages but ProtectedModifierTest class is a subclass of ProtectedModifier class that is why it is able to access the variable and method of it's super class.

Note : It must be the object of subclass to access the protected member of super class if both the classes are in different packages. For example in above program we can not access the protected member of ProtectedModifier class by creating it's object in ProtectedModifierTest class.

Public Access Modifier

A member is declared public using public keyword. This modifier doesn't put any restriction, it can be accessed anywhere. The code below declares the variable count as public.

 public int count = 0;      

Some key points about public modifier are :

  • A public member is accessible everywhere, no matter whether it's in same package or in different package.
  • Any member can be declared with public modifier whether it's a variable, method, constructor, class, interface or anything else.

Java Program of public modifier

 package testpack;
 
 public class PublicModifier {                           
    public int count = 10;       
    public void printMessage() {
       System.out.println("Public modifier program");
     }                 
  }
 package mypack; 
 import testpack.PublicModifier;
      
 public class PublicModifierTest {
    public static void main(String [] args) {                
       PublicModifier pmf = new PublicModifier();                             
       pmf.printMessage();
       System.out.println("count = "+pmf.count);           
    }
 }

Output:

Public modifier program
count = 10

As mentioned above public modifier doesn't apply any restriction that is why public members of PublicModifier class is accessible in PublicModifierTest class even though both classes are in different packages.

Table of access modifier scope

The following tables shows the accessibility/visibility scope of a member for different access modifiers in java.

Operator Within Class Within package Subclass in different package Everywhere
private Yes No No No
default Yes Yes No No
protected Yes Yes Yes No
public Yes Yes Yes Yes

Can I declare the variables of a method with public, private or protected modifiers ?.

No, variables inside a method can not be declared with public, private or protected modifier. They must be declared without any modifier.

Note : A member declared inside another member will be accessible outside only if it's outer member has same or greater accessibility modifier. For example if you declare a public variable inside a class which has default modifier, then the variable will not be accessible outside the package as it's class will be accessible within the package only.

★★★
  • A program file can have only one public class, as each public type in java must be saved in it's own file name.
  • A program can not contain public class and public interface together.
  • There can be multiple classes with default modifier in a program.
  • If you want your member's of a class should be accessible to everyone then declare your class and member both as public.
  • You should use access modifiers for a member wisely, giving unnecessary access to others limits the flexibility of changing your code.