What are Access Modifiers in Java: Everything You Need to Know in 2024

Table of Contents

What-is-Access-Modifiers-in-Java-Everything-you-Need-to-Know-in-2024 (1)

Access modifiers in Java help create access control in different parts of a program. By using access modifiers, you can restrict the access and view of Java classes, methods and variables. These modifiers are also called access specifiers. They protect your code from vulnerabilities and modifications.

To get a deep insight into it, read further.

What is an Access Modifier in Java?

Access modifiers or specifiers in Java define access restrictions for certain parts of the codes – classes, variables, methods and even the interfaces. By doing this, the access modifier creates specific access permission for the other classes to access specific parts of a Java code. In this way, the access modifier creates encapsulation within a code. As a result, it safeguards your code against security vulnerabilities and any kind of modification. 

Primarily, there are four types of access modifiers in Java – default, protected, private and public. In the next section, you will learn about each type of access modifier in detail.

Different Types of Access Modifiers in Java

As stated before, primarily, there are four types of access modifiers. So, let’s understand these different types of access modifiers in Java with examples.

Types of Access Modifiers in Java

*tutorialspoint.com

Default

When a class, method or data member has not been assigned to Java code, that means they have an access modifier by default or default access modifier in Java. With this access modifier in place, the code can only be accessible within the same package. That means their access to the specific package is private. 

So, you can easily access and work with the methods and members with the default access modifier within the same package. But if you try to access those members or methods from a different package, it will result in an error.

Here, we have created two classes, A and Hello, in the First package. Then, we tried to access the default method of class A in the Hello class. The code ran successfully because we created the two classes within the same package. Thus, it becomes easy to access the default method within another class. 

The code for the First package is 

package First;


public class A{


  int id = 1;


  void print() {

    System.out.println(“This is class A”);

  }

}


class Hello {


  public static void main(String[] args) {

A obj = new A();      //This line will call the print() method, which has the default modifier

    obj.print();

  }

}

 

Output:

This is class A

Again, we have created another package, Second. Then, we tried to access the class A of package First. But we got an error. Why? As Java doesn’t allow access to the default methods and members of a package with another class, we can’t access class A of the First package in the Second package. Thus, our code was not compiled and gave an error. 

Now, let’s code for the Second package 

package Second;


import First.A;


public class B {


  public static void main(String[] args) {

    A obj = new A();    //This line will cause a compile time error

    obj.print();

  }

}

 

Output:

print() is not public in First.A cannot be accessed from outside package

Protected

Protected access modifiers in Java allow accessing members, methods and classes within the same package. They support access through different packages when you create subclasses of the original protected package. 

Now, let’s see our first example for protected access modifier –

In this case, we have two packages, p1 and p2. The p1 package contains public class A and protected method display (). Then, we tried to access the protected method in the p2 package. For this, we have created a subclass named class B within package p2, inherited from class A. Then, we accessed the protected method of p1 by creating an object of class B.

// First Java Program to create a protected access modifier

package p1;

 

// Class A

public class A {

    protected void display()

    {

        System.out.println(“Jaro Education”);

    }

}

 

// Second Java program to illustrate protected modifier

package p2;

 

// importing all classes in package p1

import p1.*;

 

// Class B is a subclass of A. That means class B is inherited from class A.

class B extends A {

    public static void main(String args[])

    {

        B obj = new B();

        obj.display();

    }

}

 

Output:

Jaro Education

Now, in this example, we have created two packages, First and Second. In the First package, we have public class Jaro and protected method print(). Then, we tried to access the print() method in the Second package. So, in the Second package, we tried to create an instance of the Jaro class to access the protected method. But it gave an error. 

Then, we created the subclass JaroB by inheriting the Jaro class of the First package. Next, create an instance of JaroB. In this case, our program has been compiled successfully.

# Java program to create protected modifier within the First package

package First;


public class Jaro {


  int id = 1;


  protected void print() {

    System.out.println(“This is the Jaro class”);

  }

}

 

# Java program to create protected modifier within the Second package

package Second;


import First.Jaro;


class JaroB extends Jaro {


  public static void main(String[] args) {

   Jaro obj = new Jaro();

    //This line will cause an error because Jaro() is the protected method under First package

    obj.print();


   JaroB obj1 = new JaroB();

    //This line will not cause an error because JaroB() is the constructor of JaroB class which is the subclass of Jaro 

    obj1.print();

  }

}

 

Output:

Print has protected access in Jaro

This is the Jaro class

Private

If a method or data member has been declared as private, then it will be accessible within the same class only. Also, remember that if you have created another class within the same package to access the private method or member, then you can’t do it. 

‘Private’ means, the member or method is enclosed by the private class. Also, ‘protected’ means, it is only accessible through the owner class and its subclasses. Thus, top-level classes or interfaces are never declared as private. So, you can apply private or protected modifiers only on the nested classes. 

In this example, we have created two private members: a private constructor, a default parameterised constructor and a private method. So, when we tried to access the constructor A through the Main class, it gave an error because it has private access to class A. The same thing happened when we tried to access the private member and the private method within the Main class. But it will run successfully when we try to access the default parameterised constructor. 

So, from this example, you can also understand that you can’t create any instance of a private constructor.

class A {


  // Create private members

  private int roll;

  private String name;


  // Create a parameterised Constructor

 A (int n) {

    System.out.print(n);

  }


  //Now create a default constructor private

  Private A() {}


  //Private method

  private void print() {

    System.out.println(“This is class A”);

  }

}


class Main {


  public static void main(String args[]) {

    // Now create the instance of the A class

    //This will create a successful run

    A obj1 = new A(1);

      

    //Creating another instance for the A class

    //This will cause an error

    A obj = new A();

      

    //These two lines also cause errors.

    obj.name = “Jaro Education”;

    obj.print();

  }

}



Output:

constructor A in class A cannot be applied to given types;

    required: no arguments

    found: no arguments

    Reason: A() has private access in A

    

name has private access in A


print has private access in A

Public

Among the four access modifiers in Java, public has the widest scope. When you declare a class, method or data member as public, it will be accessible through any program. There is no such restriction to access the members, classes or methods with the public access modifier. 

So, in this example, we have created two packages, p1 and p2. Then, we created class A within p1. After that, we tried to access class A through another class B, which belongs to the p2. As there is no restriction for accessing the members, classes or methods with public modifiers, we have easily created an instance of class A within class B and then also accessed the display() method of class A.

# Java program 1 to create a public modifier

package p1;

public class A

{

public void display()

    {

        System.out.println(“Java Public Modifier”);

    }

}

 

# Java Program 2 to create a public modifier

package p2;

import p1.*;

class B {

    public static void main(String args[])

    {

        A obj = new A();

        obj.display();

    }

}

 

Output:

Java Public Modifier

Let’s go through this cheat sheet to understand access modifiers in Java –

Access ModifierSame ClassSame Package and SubclassSame Package and Non-subclassDifferent Package and SubclassDifferent Package and Non-subclass
Default Yes Yes Yes No No
Protected Yes Yes Yes Yes No
Private Yes No No No No
Public Yes Yes Yes Yes Yes

Importance of Access Modifiers in Java

You should use the access modifiers in Java for the following reasons –

Security

Access modifiers help restrict access to the methods and sensitive data. It helps to hide the internal coding details from potential hackers. 

Encapsulation

They hide the codes (data and methods) within a class so that other classes can’t access the internal implementation. This mechanism is called encapsulation or data hiding. It’s one of the key principles of object-oriented programming (OOP) like Java. Only the necessary functionalities can be accessed with this mechanism, and the rest of the parts are hidden. Moreover, encapsulation reduces dependencies between the classes. 

Protect Your Codes From Misuse

By enabling security and encapsulation, it prevents your methods and variables from being misused by other codes. 

Improve Readability

As access modifiers in Java directly state who can access the different components of a code or level of access, they increase the readability of that code. 

Reusability

If the classes have proper access specifiers, then you can reuse them in other projects without too much modification. 

Security for Interface

You can define stable and secured public interfaces with the help of access modifiers. The implementation of these interfaces is private. 

Access Modifiers Help You to Control the Accessibility of Your Code in Java

*dev.to

How Access Modifiers are Used in Real Projects?

Here is – how access modifiers in Java are used in real projects –

  • Public access modifiers help design public APIs of any class or interface, which is then publicly available. As a result, external classes and packages can be easily accessed. 
  • You must declare those methods and variables as private, which includes internal implementation details. By declaring them private, you can hide them from other classes. 
  • Public getter and setter methods can mark the data member variables private.
  • The JavaBean class follows some conventions. Thus, private properties need a getter and setter method. 
  • As per the access rules, FXML only initialises public methods and fields in JavaFX. 
  • To create public contracts, you should use interfaces. The interface creates an abstraction to make the code more flexible. 
  • Use package-private access for constants. But if you need to export the constants, then make them public. 
  • Use protected methods for inheritance. Also, avoid public fields for inheritance. 

Different Algorithms to Use Access Modifiers in Java

This is the basic algorithm for using access modifiers in Java

Create a Class

First, create a class. It incorporates some objects too.

Create Instance Variables for That Class

Then, define the instance variables within that class. These variables represent some data. Now, you have to specify access modifiers for each variable.

Choose an Access Modifier for the Variables

Choose an access specifier which makes your variables visible to the users. You can choose and set the access modifiers as public, private or protected as per your requirement. Now, let’s learn when to use which type of access modifiers –

  1. Use a private access modifier when you want to prohibit access to variables outside the class. It’s the most secure access modifier in Java. So, it provides the highest level of encapsulation. 
  2. If you want to make your variables accessible only within the class and its subclasses, use a protected access modifier. It’s less secure and restricted than private, but it allows inheritance. 
  3. But if you want to make your variables accessible from anywhere, use public variables. They do not have encapsulation or restriction. 
      • You can use getter (accessor) and setter (mutator) methods to manage the access of your variables. These methods not only help to manage the access of variables but also modify the variables. They create abstraction within your code, which makes your code more flexible, changeable and maintainable.

Conclusion

Access modifiers encapsulate your code by creating access restrictions for different parts of it. In this way, the four access modifiers secure your code from external usage. So, every Java developer must have a clear concept of the access modifiers to design and protect their codes from various threats and unwanted access.

So, if this blog on access modifiers in Java has caught your attention and you want to know more about it, then you must enroll in specific courses like Online Master of Computer Applications – Chandigarh University  and build a successful career in software development.

Frequently Asked Questions

What is an access specifier in Java?

Access modifiers in Java specify the level of access for a class, variable, constructor, data member or method. That means access modifiers restrict the scope of these elements in a Java program. There are four types of access modifiers – default, public, private and protected.

What are the 12 modifiers in Java?

The 12 access modifiers in Java are – 

  • Public
  • Private
  • Protected
  • Default
  • Synchronized
  • Final
  • Abstract
  • Volatile
  • Strictfp
  • Native
  • Transient
  • Static
Can a method or variable be marked as both final and public?

No, you can’t use both the keywords ‘final’ and ‘public’ for a member (method, class or variable). It creates a contradiction. But why?

The final keyword restricts modification. That means when you use this keyword in a member, you can’t inherit the member. On the other hand, the public keyword makes your code accessible through any other program. 

So, whenever you use a public keyword in a final member, the public keyword helps the subclasses call the final method. But the ‘final’ keyword restricts it from doing this, creating a collision. So, you must not use final and public keywords together. 

Can access modifiers be applied to local variables?

No, you can’t apply access modifiers on the local variables.

Access modifiers control the access or visibility of the different parts of a program. However, local variables themselves have limited scope. They only work using a specific method where they have been declared. That’s why there is no need to control their access. 

Thus, applying access modifiers to the local variables is meaningless.

What do you mean by access control in Java?

Access control is a mechanism that helps to restrict the access of specific parts of a Java program, such as classes, methods and variables. This mechanism aims to protect certain parts of Java code from severe modification and increases the level of security within the code. Thus, it hides sensitive information of that code by leveraging encapsulation. 

To implement access control in Java code, you should use access modifiers in Java, which you have already learned in this blog.  

How do access modifiers in Java relate to JavaBeans and JavaFX?

Access modifiers are helpful for both the JavaBeans and JavaFX.

  • JavaBeans require encapsulation to create reusable components, so access modifiers are needed. Also, JavaBeans prefer data protection. Thus, they use private member variables. So, they require public getters and setters to access and modify those private variables. Here, getters and setters work like access modifiers to ensure the security of the JavaBeans. 
  • For JavaFX, public member variables are required to load the FXML files. During the FXML file loading, these public variables of the controller class are directly initiated. Also, access modifiers help determine which properties of the controller class will be set for the FXML. 

That is how access modifiers are related to JavaBeans and JavaFX.

Enquiry

Fill The Form To Get More Information


Trending Blogs

Leave a Comment

Coming Soon