Java

Access Modifiers in Java

Access Modifier is an object-oriented terminology used to define the accessibility of classes, methods, and constructors. Being object-oriented programming, Java supports four different levels of access modifiers and each access modifier operates on a different level. The access modifiers may be one of the following, default, public, private, and protected. The selection of the access modifier depends on the problem that you are going to solve. This descriptive guide demonstrates the functionality of access modifiers in Java.

Access Modifiers in Java

This section provides a deep insight into access modifiers in Java. You would get a detailed description of each modifier demonstrated by an example that illustrates the functionality of each access modifier.

Public access modifier

As the name of the modifier suggests, it is least secure and the classes, methods, instances declared using public keywords have the following accessibility options:

– they can be accessed within the package/class, outside the package/class

Example

package newpack;
public class AccessMod
{
    public void show()
    {
        System.out.println("Welcome to linuxhint!");
    }
}

The code written above has the following description:

– a public class and a public method is declared that contains a print line statement.

The image of the code is provided here:

Graphical user interface, text, application Description automatically generated

The class method named show in the above code is called in the second class as shown below:

package mod;
import newpack.*;

class AccessM {
    public static void main(String args[])
    {      
        AccessMod obj = new AccessMod();
        obj.show();
    }

}

The code is described below

– the package name newpack of the class is imported

– an object of the class AccessMod (class that resides in package named newpack) is created

The image of the code and output is shown below:

Graphical user interface, application, Word Description automatically generated

From the above output, it is concluded that the public access modifiers can access the objects of a class that is outside of that class and package as well.

Private Access Modifier

Contrary to the public class, private methods/varibales can be accessed only inside of the class. A private methods/variables cannot be accessed:

– outside the package

– within the package (but out of the class)

Example 1: Outside of the Package

package newpack;
class AccessMod
{
    private void show()
    {
        System.out.println("linuxhint!");
    }
}

The description of the code is provided below:

– the show method is declared with a private modifier

Graphical user interface, text, application Description automatically generated

Now, the following code tries to execute the show method from the AccessMod class.

package mod;
import newpack.*;

class AccessM {
public static void main(String argos[])
    {
AccessMod obj = new AccessMod();
obj.show();
     }  
}

A new class named AccesM is created in mod package. The newpack package is imported in this package as we have to create an object of the class named AccessMod (that resides in newpack’s class).

Graphical user interface, text, application Description automatically generated

It is clear from the output that AccessMod and the associated objects could not be accessed outside of the package.

Example: Outside of the class (same package)

package lh;
class prim {
    private void pvt() {
        System.out.println("LinuxHint");
              }        
}

The code is described as,

– a class named prim is created in lh package. The prim class contains a private method named pvt.

Now, to verify the private access modifier, the code provided below is used.

package lh;
class second {
    public static void main(String[] main){
    prim obj=new prim();
obj.pvt();
    }
}

The package of both classes is same, but the class named second tries to create an object of pvt(). The pvt() is a method in prim class.

It is observed from the output that, pvt() method cannot be accessed due to its private access modifier.

Default Access Modifier

The data members declared using default keywords are accessible within the same package only. It falls in between private and protected access modifiers and thus it is more secure than protected and least secure than private.

Example 1: Outside the package

package newpack;
class Def {
    static void main(String[]args) {
        System.out.println("A default class");
    }
}

The description of the code is as follows,

– a default class is created named Def and it contains the main method

– a print line statement is executed inside the main method

Graphical user interface, text, application, Word Description automatically generated

To test the accessibility of the default class, the following lines of code are used.

package lh;
import newpack.*;
class deft {
    static void main(String[]args) {
        Def test= new Def();
        test.main();
    }
}

The code is described as,

– imported the package named newpack

– created a new class deft

– created an object of the class Def in the main method of the deft class

Graphical user interface, text, application Description automatically generated

The output shows that the accessibility of the Def class must be changed to the public to be accessed in a class of other packages.

Example 2: Outside the class (within the same package)

The following code creates a default method for a class named prim.

package lh;
class prim {
     void pub() {
        System.out.println("Default Access Modifier");
              }        
}

A default method named pub() is defined in the class prim.

To verify its accessability, let’s have a look at the following code.

package lh;
class second {
    public static void main(String[] main){
    prim obj=new prim();
obj.pub();
    }
}

An object of the pub() method is created in another class(which resides in the same package).

It is observed from the output that the object of the pub() method is executed successfully and thus it is concluded that the methods declared using default access modifiers can be used within the same package but in different class.

Protected Access Modifier

The methods or data members that are declared using protected keywords are accessible within the class or the other classes in the same package. It cannot be accessed outside of the package but a subclass of the other packages can access the protected methods.

Example: Using sub-class of the same package

package newpack;
class AccessMod
{
    protected void show()
    {
        System.out.println("linuxhint!");
    }
}

The show() method is declared with protected privileges:

Graphical user interface, application, Word Description automatically generated

The method is accessed in the AccessM (subclass of the same package where the AccessMod lies) and the process is carried out using the following code:

package newpack;

class AccessM extends AccessMod {
public static void main(String args[])
    {      
        AccessMod obj = new AccessMod();
        obj.show();
    }
}

The output image of the code is provided below:

Graphical user interface, text, application, Word Description automatically generated

Now, let’s elaborate the difference between default and protected access modifiers using the following example. The default access modifiers cannot be accessed by subclasses (outside the package), however, we will access a protected method by using a subclass.

Example 2: Using subclass of other packages

package lh;
public class Prot {
    protected  void display() {
        System.out.println("Welcome to LinuxHint!");
    }
}

In the above code, a protected method is declared inside a class that contains a simple print line statement.

The code written below will create and access the object of the protected method shown in the above image.

package newpack;
import lh.*;
   class protmod extends Prot {
    public static void main(String args[])
    {      
    protmod obj = new protmod();
    obj.display();
    }
}

You would observe that,

– the package lh is being imported into the package newpack

– a subclass(of Prot class) named protmod is declared

– object of the protmod class named obj is used to get the content of the display() method (of Prot class).

The output shows that the display() method contained inside the Prot class is used in the subclass of the Prot class.

Conclusion

Java’s access modifiers allow you to determine the accessibility level of methods, classes, variables, and constructors. This article provides the functionality of the access modifiers that can be used in Java. The access modifers such as private, public, protected, and default are exercised using various examples. Lastly, it is concluded that the private modifiers set the most secure platform whereas the public modifiers are considered the least secure one.

About the author

Adnan Shabbir