Advanced
Data Structures Algorithms & System Design(HLD+LLD)
by Logicmojo

Top tech companies experts provide live online training

Learn Data Structures, Algorithms & System Design

Online live classes from 4 to 7 months programs

Get job assistance after course completion

Download Course Brochure

Back to home
Logicmojo - Updated Dec 20, 2022



Classes, variable methods, and constructor access levels in Java are specified via access modifiers. It aids i n changing a variable's value. They sometimes go by the name "visibility modifier." I shall explain the significance of access modifiers in Java through the use of this blog.

What does Java's Access Modifier do?

Java uses access modifiers to regulate who has access to or authorization to execute a piece of code. Its primary purpose is to regulate how easily a programme or block of code is visible or accessible. It specifies which programme elements—such as classes, methods, constructors, etc.—will be available to the other programme member.
In Java's Object-Oriented Programming OOPs, the idea of Encapsulation goes hand in hand with Access Control.

Why are Java's access modifiers and control mechanisms required?

Simply said, it aids in the security and legitimacy of the code block. If you make your code accessible to the general public, it can experience certain undesirable alterations. We use access modifiers to restrict access control to prevent these scenarios. We can separate the bits of code into public, private, and protected categories by announcing the access control.

Types Access Modifiers in Java

The access modifiers or specifiers listed below can be used to restrict access to a code block.

      ⮞ Default Access Modifiers

      ⮞ Private Access Modifiers

      ⮞ Protected Access Modifiers

      ⮞ Public Access Modifiers

Default Access Modifiers

The class's methods are not given with any modifiers when they are instance members. It is claimed that it comes with a default modifier. Only within the same package is it possible to access instance members and methods declared with the default modifier. Consequently, it is also known as package-private.
Let's use a Java application to understand the default modifier.
accessing the default class's methods and members.

package pack1;
class default_demo
{
	void show()
	{
		System.out.println("Use of Default Access Modifier");
	}
}
 
package pack2;
import pack1.*;
 
class Main1
{
	public static void main(String args[])
	{
		//Trying to access class default_demo from package pack1
		default_demo obj = new default_demo();
 
		obj.show();
	}
}

💡Compile time error

Explanation:
As there is no access modifier following the class name demo_default in this instance, the default (package-level). As a result, we are unable to access the class demo_default in another package.

Private Access Modifiers

The class in which they are declared determines who has access to any private methods or data members.
Because of this, top-level classes or interfaces cannot be defined as private.
"Only viewable inside the enclosing class" is what private means.
"Just noticeable inside the enclosing class and any subclasses" is what protected means.
You cannot create an object of a class from outside the class if it has a private constructor. Classes cannot have the private access modifier applied to them.

class Access_Modifier_Demo {
    private String str;
}

public class Main 
{
    public static void main(String[] main){

        Access_Modifier_Demo strs = new Access_Modifier_Demo();
        strs.str = "Hey this is private";
    }
}

An error will be produced by this code. Why? 'str' is a private variable from a subclass of the main class that we are attempting to access.
A private variable cannot be accessible outside of the block that it is defined in.

class Access_Modifier_Demo {
    private String str;
    public String getterMethod() {
        return this.str;
    }
    public void setterMethod(String str) {
        this.str= str;
    }
}
public class Main {
    public static void main(String[] main){
        Access_Modifier_Demo strs = new Access_Modifier_Demo();

        strs.setterMethod("Accessing Private Variable");
        System.out.println(strs.getterMethod());
    }
}

How would you access the private variable now? What method will you use? You must utilise a getter and setter method in order to access a private variable or method from a different class.
The private variable "str" is accessible from the outer class in the example above. In Java, the methods are referred to as getter and setter methods, respectively.

The getter method (getterMethod()) is used to access a variable after it has been set by the setter method (setterMethod()). this keyword is used to refer to the class variable inside of setterMethod().

Public Access Modifiers

It's a key phrase. A class member, such as a variable, method, or data member, can be accessed from anywhere inside the programme if a public access modifier is prefixed to it. In other words, they can be accessible both from inside and outside of the various classes.
It also covers access from both inside and outside the packaging of the same item. The members can be accessed globally, including variables, methods, and other data members.
We may give members access the easiest way possible by using public access modifiers. Members of the public access modifier are not subject to any limitations. In comparison to the other access modifiers, it therefore has the broadest accessibility or visible scope.

Let's use a Java programme to explain the public modifier.
Think about two packages, First and Second, each containing two public classes.
One instance member and one method, namely print, are present in the Demo class of the First package (). Both belong to the public type. Let's try accessing them in a new class of packages, specifically in the Second package.

package First;

public class Demo {
  public int id = 1;
  public void print() {
    System.out.println("This is the Demo class");
  }
}


package Second;

import First.Demo;

public class Logicmojo {

  public static void main(String[] args) {
    Demo ob = new Demo();
    System.out.println(ob.id);
    ob.print();
  }
}



Learn More

Protected Access Modifier

With the aid of a child class, we can employ protected modifier methods, instance members, and access them in another package, meaning we must extend the class that has protected members in the other package.
By making an object of a class that has protected members and functions, we are unable to directly access them.
Let's use a Java programme to explain the protected modifier.

There are two packages, First and Second. We are attempting to access this function in another package in two different ways by using the First package, which has one public class and one protected prefixed method.
establishing a Demo class instance (declared in First package)

inheriting the Demo class from the Second package's Logicmojo class.

package First;

public class Demo {

  int id = 1;

  protected void print() {
    System.out.println("This is the Demo class");
  }
}

package Second;

import First.Demo;

class Logicmojo extends Demo {

  public static void main(String[] args) {
    Demo ob = new Demo();
    //This line will cause an error
    ob.print();

    Logicmojo ob1 = new Logicmojo();
    //This line will not cause an error
    ob1.print();
  }
}

Because we cannot access the protected method outside of its own package, the line ob.print() will result in an error; however, ob1.print() will not result in an error because we can access the protected method by inheriting from some other class of other packages.

Real life Example

      ⮞ Anyone with access to the Internet can view this status if you make it public (Anyone On or Off Facebook). [Specifiers for Public Access]

      ⮞ If you choose to make this status "just for me" public. This status is only visible to you. [Specifiers for Private Access]

      ⮞ Your status will only be visible to your friends and the friends of your friends if you choose to make it available to friends or friends of friends. Facebook and the Internet are not used by everyone. S[pecifiers for Protected Access]

      ⮞ Only your friends will be able to see your status if you set it to be "Friends" only. not all of your Facebook friends or your friends' friends. [Indicators of Default Access]

Diamgrammatic Explanation of Access Modifiers in Java

Access ModifierSame classSame package subclassSame package non-subclassDifference Package subclassDifferent package non-subclass
DefaultYesYesYesNoNo
PrivateYesNoNoNoNo
ProtectedYesYesYesYesNo
PublicYesYesYesYesYes


Access modifiers for Java with method Overriding

The major restriction for overriding methods is that they shouldn't be more restrictive.
Java's private access modifier has the most limited reach and forbids overriding methods within the same package.
The other access modifiers, however, let method overriding both inside the same package and between packages.

class Demo {

  int a = 5;
  
  private void print() {
    System.out.println("This is the Demo class");
  }
}

class Main extends Demo {

  @Override
  private void print() {
    System.out.println("This is the print class of the Main");
  }

  public static void main(String[] args) {
    Main ob = new Main();
      
    //Calling the override method
    ob.print();
  }
}

JVM will give a compilation error if we attempt to override the parent class's private function. We can see the scope of private modifiers in the visual representation of access modifiers in Java since we can only access private methods within their own class. Still, we are attempting to use the concept of method overriding to access that function in the other class. An error will result from this.

Access Control and Inheritance

If you subclass a class, the methods in that subclass are not allowed to have less accessible access modifiers than the methods in the superclass.
For example, if a method is public in the superclass, it must also be public in the subclass. If a method is protected in the superclass, it must also be protected or public in the designated subclass.
Privately declared methods are not at all inherited.

Non-Access Modifiers

Non-access modifiers notify the JVM about a class's, method's, or variable's characteristics. There are seven different kinds of non-access modifiers in Java.

      ⮞ They are - static

      ⮞ final

      ⮞ abstract

      ⮞ synchronized

      ⮞ volatile

      ⮞ transient

      ⮞ native

Access modifiers for classes or interfaces in Java

The following four access modifiers in Java can encapsulate methods and data members. In order of increasing degree of restriction, the access modifiers are enumerated.
private (available within the class where defined) (accessible within the class where defined)
instead, package-private (when no access modifier is specified)
protected (only available to classes that directly subclass your class within the current or another package)
public (available from any class) (accessible from any class)
However, when stated independently of any other class, the classes and interfaces themselves can only have two access modifiers.
Note: All access modifiers are permissible for nested interfaces and classes.
A class or interface cannot be declared with the access modifiers private or protected.

FAQs

What makes access specifiers essential?

To secure sensitive information from direct access, access specifiers are used for encapsulation and offer various forms of limitations based on the requirement.

What modifiers don't apply to the class?

The private and protected modifiers cannot be used for the class since the JVM's external calling mechanism won't be able to execute the class if they are used due to their restricted scope.

Conclusions

This concludes our discussion of "Access Modifiers in Java." I sincerely hope that you learned something from it and that it improved your knowledge. You can consult the Java Tutorial if you want to learn more about Java.

Good luck and happy learning!

Logicmojo Learning Library