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

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

12 Apr 2024
Intermediate
15.7K Views
14 min read
Learn via Video Course & by Doing Hands-on Labs

Java Programming For Beginners Free Course

Access Specifiers in Java: An Overview

Access Specifiers in Java 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 Java tutorial, we’ll explain each of the four major Java access modifiers in depth. 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 Specifiers 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 Java 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.

Read More - Top 50 Java Interview Questions

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".

Real Life example of an Access Modifier in Java?

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

Types of Access Modifiers in Java

1. 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 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.

Default Access Modifiers - 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();
 }
}

Explanation

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 to access and use it. When you execute this code in our Java Online Compiler, the following output will be generated.

Output

Compile time error

2. 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.

Read More - Java Programmer Salary In India

Private Access Modifiers - 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";
  }
}

Explanation

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); 

3. 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.

Protected Access Modifiers - 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();
 }
}

Explanation

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

4. 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.

Public Access Modifiers - 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();
  }
} 

Explanation

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. The execution of the above code in the Java Compiler gives the following output.

Output

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

Java algorithm for using an access modifier

  • Class Definition: To represent the managed object, create a class.
  • Instance Variables: Define instance variables in the class to store managed data.
  • Access Modifiers: To regulate visibility, specify the private, protected, or public access modifiers for instance variables.
  • Private Access Modifiers: To ensure maximum encapsulation, use the Private Access Modifier on variables that are only available within the class.
  • Protected Access Modifier: For variables that are inheritable within the class and its subclasses, use protected.
  • Public Access Modifier: Use the public access modifier for variables that may be accessed from anywhere and require limited encapsulation.
  • Accessor and Mutator Methods: To manage variable access for abstraction, maintainability, and testability, use accessor and mutator methods (getter and setter).

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!

FAQs

Q1. What are the access modifiers used in Java?

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

Q2. 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.

Q3. 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.

Q4. 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.
Share Article
Live Training Batches Schedule
About Author
Shailendra Chauhan (Microsoft MVP, Founder & CEO at Scholarhat by 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.
Self-paced Membership
  • 22+ Video Courses
  • 750+ Hands-On Labs
  • 300+ Quick Notes
  • 55+ Skill Tests
  • 45+ Interview Q&A Courses
  • 10+ Real-world Projects
  • Career Coaching Sessions
  • Email Support
Upto 60% OFF
Know More
Accept cookies & close this