Java Access Modifiers Explained

Java provides access modifier keywords that allow or restrict access to classes, methods, and member variables. We call these Java Access Modifiers. There are four different types of access modifiers that are listed below.

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

Public Access Modifier

The public access modifier is identified using the keyword public. So if you have a class, method, constructor, interface that is declared public, those items can be accessed from anywhere. The public access identifier has the widest scope of access.

public class JavaCodedepot 
{
    //Variables and methods....
}


Protected Access Modifier

The protected access modifier is identified using the keyword protected. The methods or variables declared as protected are only accessible within same package or within a sub classes of a different java package.

public class JavaCodeDepot
{
    protected void showDetails()
    {
        System.out.println("Details: "+details);
    }
{


Private Access Modifier

The private access modifier is identified using the keyword private. The methods and variables declared as private are only accessible in the class in which they are declared. The private access modifier is the most restrictive access level. It is important to note that class and interfaces can’t be private.

public class JavaCodeDepot
{
    private void loadJCDCodeSamples()
    {
        //Load the JavaCodeDepot samples and tutorials
    }
{


Default Access Modifier

The default access modifier is identified by the absence of a keyword. If we do not use an access modifier keyword, we are essentially assigning the default access. If a class, method, variable has no access modifier assigned, it will essentially be available by any other class contained within the same package.

//Variable with default access
String jcdString = "Java Code Depot";

//Method with default access
int calculateNumber 
{
    return 0;
}


Add a Comment

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