What is access modifier?

Access modifiers are keywords available in Java that defines the scope/availability of any class, variable or method in the program or outside of the program. The main purpose of access modifiers is to implement an encapsulation, that separates the interface of a type from its real implementation or in simple words access modifiers are used to implement the data hiding feature.

Access modifier keyword

Java has four types of access modifiers – 

  1. default (Without keyword)
  2. private 
  3. protected
  4. public

Default access modifier

In default access modifier we don’t need to declare/provide any access modifier keyword. Fields, methods, or classes declared without the access modifier keyword can be used by any other class in the same package.

Example

class DefaultExample {
 
    void sayHello(){
        System.out.println("Hello");
    }
 
}

Private access modifier

A private access modifier can only be used with methods, variables, and inner classes. The scope/availability of privately declared field, method or the inner class is only within the class where it is declared.

Example

class PrivateExample {
 
    // A private method
    private void sayHello(){
        System.out.println("Hello");
    }
 
}

Protected access modifier

Protected access modifiers are very similar to private access modifiers, but they can only be accessed by subclasses. Protected access modifier cannot be used with classes.

Example

class ProtectedExample {
 
    // A method declared as protected
    protected void sayHello(){
        System.out.println("Hello");
    }
 
}

Public access modifier

Classes, methods, constructors, interfaces, etc. declared as public can be accessed from any other class. Thus, fields, methods, and blocks declared in public classes can be accessed from any class.

Example

public class PublicExample {

    // A method declared as public
    public void sayHello(){
        System.out.println("Hello");
    }

}