Access Modifiers in Java


What are access modifiers?

Access modifier in Java works as per their name suggests — they help to limit the scope of a class, function, Object, variable, or data member.

Here, in the page we will discuss more about the access modifiers that are used in java.

What are modifiers?

In Java, to change the meaning of the definitions, We can add modifiers like keywords etc. Modifiers in the Java language come in a vast variety.

There are two types of Modifiers:

  1. Non – Access modifier
  2. Access modifier

Non-Access Modifiers:

Non-access modifiers notify the JVM about a class’s, method’s, or variable’s characteristics. There are several different types of non-access modifiers that are used in Java.

Access Modifiers:

The accessibility (visibility) of classes, interfaces, variables, methods, constructors, data members, and setter methods in Java is controlled by access modifiers.
There are 4 types of access modifiers present in Java, these are :

  • public
  • protected
  • private
  • default
access-modifier in java

Default Modifiers:

if the programmer don’t mention any access modifier explicitly then by default, default modifier is called. The default modifier is accessible only within package. It cannot be accessed from outside the package.


class Lakshit{
    void default_Modifier(){
        System.out.println("Default Modifier is invoked");

Public Modifier:

Public methods, variables and classes can be accessed from anywhere in the program. There are no restriction on the public modifiers.


public class PrepInsta{
    public int Lakshit;    // Public variable
    public void display(){    // Public Method
        System.out.println("This is PrepInsta");

Protected Modifier:

We can’t access the protected members of a class outside the package. We can access the protected package within the block as well as from sub classes.


class PrepInsta{
    protected void display(){    // Protected Method
        System.out.println("I am Prepster");

class prime extends PrepInsta{
    public static void main(String[] args) {
        prime prime = new prime();

Private Modifier:

When variables and methods are declared private, they cannot be accessed outside of the class. private members can only be accessed within the class.


class PrepInsta{
    private int enroll_no;    // Private members

public class Main{
    public static void main(String[] main){
        PrepInsta Prep = new PrepInsta();
        Prep.enroll_no = 282290;

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription