Access Modifiers in Java: Default, Private, Public, Protected

Shailendra Chauhan  12 min read
22 Sep 2023
Intermediate
1.27K Views

Access Modifiers in Java: An Overview

Access modifiers allow you to define which sections of code can be seen or used by other classes, and understanding them is key to writing efficient programs. In this blog post, we’ll explain each of the four major Java access modifiers in-depth –access modifiers in Java, access modifiers in Java with example, Java Access Modifiers public, private, protected, and default – and what they do differently when it’s appropriate to use each one, and how they interact with inheritance. Get ready to boost your confidence in being able to use Java appropriately, with the help of Java training. If you want to learn Java, understanding access modifiers is essential as they play a crucial role in managing the accessibility of different elements within your code.

What is an Access Modifier in Java?

Access Modifiers in Java generally control the permissions of a block of code. It assists the accessibility and visibility of the program by defining which part of the program would be visible to the users as well as other members. These access modifiers can be used in loops in Java to provide security and authentication to the program. If the developer wants to allow the code to be publicly available, it might need some undesired changes. To avoid this situation, developers control the access of the program by using Access Modifiers. They segregate the code to be public, private, or protected according to their needs.

Real Life example of an Access Modifier in Java?

As a real-time example, we can choose Facebook where users can control their posts. There are three types of Access Modifier such as, "Public Access Specifier", "Protected Access Specifier" and "Private Access Specifier"

  • If anyone wants to make the status visible to the public they can choose "Public Access Specifiers".
  • If anyone wants to make their status visible to only their friends it is called a "Protected Access Specifier".
  • Lastly, if someone wants to make the status visible for only themselves then they can use the "Private Access Specifier".

Types of Access Modifiers in Java

There are four types of Access Modifier in Java:

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

Default Access Modifiers in Java

  • There are several reasons to learn about Java, especially concerning access modifiers.
  • If any data or the developers of that program do not specify any access modifier, then that means it is in the default state.
  • In the default stage, all the methods and classes, including the data members, are package-level.
  • Default Access Modifier in Java means the methods and classes are accessible only in one particular or same package, which is a collection of related classes.
  • Understanding these access modifiers is essential for Java developers as it helps in controlling the visibility and accessibility of different components within the code, leading to more secure and organized software development.

Example

// Java program to show default modifier

package p1; //Package named P1 declaration

// Class default_DNT is having Default(Package-level) access modifier

class default_DNT
{
  void show()
  {
    System.out.println("Use of Default Access Modifier");
  }
}

package p2; //Package named P2 declaration

import p1.*; //Importing P1 to P2 for accessing the class member functions

class Main1
{
  public static void main(String args[])
  {
    //Trying to access class default_DNT from package p1
    default_DNT obj = new default_DNT();
    obj.show();
  }
}

There are two packages in this Java code: p1 and p2. It creates a class called default_DNT with a default (package-level) access modifier in the p1 package. It tries to import the default_DNT class from the p1 package into the Main1 class in the p2 package in order to access and use it.

Output

Compile time error

Private Access Modifiers in Java

  • Private Access Modifier in Java is a private keyword that is mainly used for a private class, constructor, or method.
  • The methods of private modifiers can not be accessed by other users other than their native class.
  • The data members of private modifiers are only available in their defined class.

Example

class Access_Modifier
{
    // private variable
    private String str;
}
public class Main
{
    public static void main(String[] main)
    {
        // create an object of Access_Modifier class
        Access_Modifier a = new Access_Modifier();

        // Try to access private variable from another class
        a.str = "This is private";
    }
}

An Access_Modifier class with the private variable "str" is shown in this Java example. In the Main class, the private access modifier prevents access to the private variable "str" from an object of the Access_Modifier class, which is attempted.

Output

//AccessModifiers.java:24: error: a has private access in AccessModifiers
 System.out.println("value of a (direct access)= " +obj.a); 

Protected Access Modifiers in Java

  • The methods and the members of Protected Access Modifiers in Java are only accessible and visible to their classes and their inherited classes.
  • Protected Access Modifiers use the keyword "protected" to do the declaration.
  • This concept follows the Inheritance methods of object-oriented programming.

Example

// Class Parent is the Parent class
class Parent
{
protected void display() //protected method
  {
    System.out.println("Testing Protected Access Modifier");
  }
}

//Class child inherits the Parent class
class Child extends Parent
{
public static void main(String args[])
{ //obj created to access the protected method display()
  Child obj = new Child();
  obj.display();
 }
}

There are two classes in this Java example: Parent and Child. The notion of inheritance and protected access is shown by the reality that the Child class derives from the Parent class and can access the protected method "display()" of the Parent class thanks to the protected access modifier.

Output

Testing Protected Access Modifier

Public Access Modifiers in Java

  • Public Access Modifier in Java is used for making a method or data member accessible for everyone and every platform.
  • This access modifier uses the "public" keyword to make the data public in Java.

Example

class AccessModifiers
{
    public int a;
    public int b;

    public void setVal()
    {
        a=7;
        b=3;
    }

    public void getVal()
    {
        System.out.println("a= " +a);
        System.out.println("b= " +b);
    }
}

class mainDemo
{
    public static void main(String args[])
    {
       AccessModifiers obj = new AccessModifiers();
       //Can directly access public members
       System.out.println("Value of a (direct access)= " +obj.a);
       System.out.println("Value of b (direct access)= " +obj.b);
       obj.setVal();
       obj.getVal();
    }
} 

The "AccessModifiers" class in this Java example defines public integer variables "a" and "b," as well as public methods "setVal()" and "getVal()" for changing and retrieving their values. An object of "AccessModifiers" is created in the "mainDemo" class to show how to directly access the public members "a" and "b," change their values, and print the results using the class's methods.

Output

Value of a (direct access)= 0
Value of b (direct access)= 0
a= 7
b= 3

FAQs

1. What are the access modifiers used in Java?

Public, private, protected, & default (package-private) are the access modifiers in Java.

2. How to check access modifiers in Java?

The visibility of class members (fields, methods, and classes) in different scopes, such as public, private, protected, or package-private (the default), can be used to check access modifiers in Java.

3. What are the 12 access modifiers in Java?

12 Modifiers in Java are public, private, protected, default, final, synchronized, abstract, native, strictfp, transient, and volatile.

4. What is the default access modifier in Java?

Since package-private is Java's default access modifier, only other members of the same package can access its members.

5. What is public vs protected vs private in Java?

In Java, the terms "public," "protected," and "private" provide varied degrees of visibility and encapsulation. In Java, "public" makes a member accessible from any class, "protected" permits access inside the same package and by subclasses, and "private" restricts access to only within the declaring class.

Summary

This article gives a clear idea about the Access Modifiers in Java and its types. If you want to learn Java, in this article, every type of Access Modifier has been vastly evaluated with examples. They can be seen as the 'gatekeepers' that help protect and secure our code, control the data privacy within a system, and aid in keeping object-oriented programming consistent. We hope this guide, including Java Certification Training, gave you an in-depth look into how each of these access modifiers works and how you can use them to protect your code from malicious actors or users. It's up to you now to practice using the various access modifiers and protect your coding projects!

Share
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at DotNetTricks)

Shailendra Chauhan is the Founder and CEO at ScholarHat by DotNetTricks which is a brand when it comes to e-Learning. He provides training and consultation over an array of technologies like Cloud, .NET, Angular, React, Node, Microservices, Containers and Mobile Apps development. He has been awarded Microsoft MVP 8th time in a row (2016-2023). He has changed many lives with his writings and unique training programs. He has a number of most sought-after books to his name which has helped job aspirants in cracking tough interviews with ease.
Accept cookies & close this