What are Access Modifiers in Java: Everything You Need to Know in 2024
Table of Contents
- jaro education
- 15, May 2024
- 4:00 am
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.
*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 Modifier | Same Class | Same Package and Subclass | Same Package and Non-subclass | Different Package and Subclass | Different 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.
*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 –
- 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.
- 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.
- 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.