In this tutorial, we will learn about the Access Modifiers in Java, or its types, and how to use them with the help of examples.

What is a Access Modifiers in Java

This modifier specifies the scope of a field, method, constructor, or class. We can change access level of field, constructor, method, and class by applying the access modifier on it.

There are four types of Access Modifier

  • Private Access Modifier
  • Public Access Modifier
  • Protected Access Modifier
  • Default Access Modifier

Private

The Private access level of a private modifier is only within the class. It cannot be access from outside the class.

Example

class Royal {
    private String name;
    public String getName() {
        return this.name;
    }
    public void setName(String name) {
        this.name= name;
    }
}
public class Accessesdpps {
    public static void main(String[] main){
        Royal d = new Royal();
        d.setName("Basic Engineer");
        System.out.println(d.getName());
    }
}
Private Access Modifier

Let’s run the code

Input Value
Output Value

Public

The Public access level of a public modifier is everywhere. Its means, can be access from within the class, outside the class, within the package and outside the package.

Example

public class A{  
protected void msg(){System.out.println("Basic engineer");}  
}  
Public Access Modifier

Let’s run the code

Input Value
  class B extends A{  
  public static void main(String args[]){  
   B obj = new B();  
   obj.msg();  
  }  
}
Public Access Modifier

Let’s run the code

Input Value
Output Value

Protected

The Protected access level of a protected modifier is within the package and outside the package through child class is knows as Protected Access.

Example

public class AccessA{  
    protected void msg(){System.out.println("Basic Engineer");}  
    }  
Protected Access Modifier

Let’s run the code

Input Value
class AccessB extends AccessA{  
    public static void main(String args[]){  
     AccessB obj = new AccessB();  
     obj.msg();  
    }  
  }  
Protected Access Modifier

Let’s run the code

Input Value

Output Value

Output Value

If you have any queries regarding this article or if I have missed something on this topic, please feel free to add in the comment down below for the audience. See you guys in another article.

To know more about JAVA Wikipedia please click here .

Stay Connected Stay Safe, Thank you


Basic Engineer

Hey Readers! We have more than fifteen years of experience in Software Development, IoT, Telecom, Banking, Finance and Embedded domain. Currently we are actively working on Data Science, ML and AI with multiple market leaders worldwide. Happy Reading. Cheers!

0 Comments

Leave a Reply

Avatar placeholder

Your email address will not be published. Required fields are marked *