Access Modifiers in Java
Access modifiers are keywords which define the accessibility of a class and its members. Access modifiers are used in Java to control the visibility (accessibility) of classes, interfaces, variables, methods, constructors, data members, and setter methods.
Contents
Best-suited Java courses for you
Learn Java with these high-rated online courses
What is Access Modifier in Java?
Access Modifiers in Java are used to control the access or permission of a block of code. Its basically used for controlling the visibility or accessibility of a program/ block of code. It defines what parts of the program (such as classes, methods, constructors, etc.) will be accessible to the other member of the program.
Access Control comes along with the concept of Encapsulation in Object-Oriented Programming OOPs in Java.
Why do we need Access Control and Access Modifiers in Java?
In simple terms, it helps to secure and provide authenticity to the code block. If you allow your code to be publicly available, it might undergo some undesired changes. To avoid such situations, we limit the access control using access modifiers. By declaring the access control, we can segregate the pieces to code to be public, private, and protected.
Also Read: Difference between JDK, JRE, and JVM
Real life Example of Access Modifiers in Java
While updating your Facebook Status, it gives you 3 options for the post.
- If you make this status visible for Public, anyone can see this status on Internet (Anyone On or Off Facebook). [Public Access Specifiers]
- If you make this status visible for Friends or Friends of friends, then your status will be only visible for your friends and your friends friends. Not for everyone on Facebook or Internet. [Protected Access Specifiers]
- If you make this status visible “only for me”. No one can see this status except you. [Private Access Specifiers]
Types of Access Modifiers in Java
Following are various access modifiers or access specifiers to achieve access control over the code block.
- Default Access Modifiers
- Private Access Modifiers
- Protected Access Modifiers
- Public Access Modifiers
Summarized view of Accessibility of Access modifier in Java
Accessibility | Default | Private | Protected | Default |
Inside Same Class | Yes | Yes | Yes | Yes |
Subclass of a Class | Yes | No | Yes | Yes |
Same Package Different Class | Yes | No | Yes | Yes |
Different Package’s Subclass | No | No | Yes | Yes |
Different Package Non-Subclass | No | No | No | Yes |
Read: Java Operators Explained
Must explore: Free Java Courses Online
Let’s learn about each Access Modifier in detail with examples.
More topics for you to explore:
Default Access Modifier
If data members have no access modifier specified, it means it’s the default. By default all the data members such as classes and methods are package-level. It implies that data classes and methods are accessible only with the same package. FYI, for now, think of the package as a folder or collection of related classes.
Example:
// Java program to show default modifierpackage p1; //Package named P1 declaration // Class default_AM is having Default(Package-level) access modifierclass default_AM{ void show() { System.out.println("Use of Default Access Modifier"); }} package p2; //Package named P2 declarationimport p1.*; //Importing P1 to P2 for accessing the class member functions class Main1{ public static void main(String args[]) { //Trying to access class default_AM from package p1 default_AM obj = new default_AM(); obj.show(); }}
Explanation:
Here, as the class name default_AM does not follow any access modifier, it means it’s the default (package-level). Hence, we can’t access class default_AM in a different package.
Output:
Read: Implementing Array in Java
Explore: Java Online Courses & Certifications
Private Access Modifier
If a data member is declared using a private keyword, it means it’s a private class, method, or constructor. A private access modifier defines a method that can’t be accessed outside its native class, not even by its sub-class (or child-class). Hence, the private data members are only available in the class where they are defined.
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:
This code will result into an error. Why? Because we are trying to access ‘str’ – a private variable from a different class to the main class.
NOTE: Private variable cannot be accessed outside the defined block.
Output:
Now what if you want to access the private variable. How will you do it?
Well in-order to access private variable/ method from a different class you need to use a getter and setter method for it.
class Access_Modifier { private String str;
// getter method public String getterMethod() { return this.str; } // setter method public void setterMethod(String str) { this.str= str; }}public class Main { public static void main(String[] main){ Access_Modifier a = new Access_Modifier();
// access the private variable using the getter and setter a.setterMethod("Accessing Private Variable"); System.out.println(a.getterMethod()); }}
In the above example, the private variable ‘str’ is accessed from the outer class. The methods: getterMethod() and setterMethod() are called getter and setter method in Java.
The setter method (setterMethod()) assign value to the variable and the getter method (getterMethod()) is used to access the variable.
this keyword inside the setterMethod() is used to refer to the variable of the class.
Read: Loops in Java
Protected Access Modifier
The protected data members and methods are visible and accessible in their own class as well as their inherited class. The declaration of protected access modifier uses the keyword protected. This modifier usually comes under the OOP concept of Inheritance.
Example:
// Class Parent is the Parent classclass Parent{protected void display() //protected method { System.out.println("Testing Protected Access Modifier"); }}//Class child inherits the Parent classclass Child extends Parent{public static void main(String args[]){ //obj created to access the protected method display() Child obj = new Child(); obj.display();} }
Explanation:
Here, the protected keyword with method display() made it accessible to its subclasses. Hence, the child class is able to access the display() method in the Parent class.
Output:
Also, Read: Constructors in Java Explained
ava Interview? Here’s a list of most asked Top 160 Java Interview Questions and Answers for 2022.
Public Access Modifier in Java
The public access modifier, when used with a data member or method, makes it accessible everywhere, even outside the class and package. To make a data member or method public, we use the public keyword in Java.
Example:
class AccessModifiers{ public int a; public int b; public void setVal() { a=5; b=2; } 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:
As data members (variables) and methods (functions) are declared public. Hence they are accessible everywhere.
Output:
Read Next:
Conclusion
Access modifiers are very important when you want to specify the visibility of a block of code. In this post, we discussed access modifiers in java with examples in the above article. Hope you learned and understood the concept clearly. If you have any queries feel free to reach us for doubts in the link below. Till then, Happy Learning!
FAQs
What is Access control?
It helps to control the visibility or accessibility of data members (such as variables, methods, constructors, class, etc). It comes under the concept of data encapsulation in Java.
What are Access Modifiers in Java?
Access modifiers are keywords in Java which define the accessibility of a class and its members. They are used in Java to control the visibility (accessibility) of classes, interfaces, variables, methods, constructors, data members, and setter methods.
How many types of Access Modifiers are in Java?
There are 4 types of Access Modifiers in Java: default (no keyword), public, private, and protected.
This is a collection of insightful articles from domain experts in the fields of Cloud Computing, DevOps, AWS, Data Science, Machine Learning, AI, and Natural Language Processing. The range of topics caters to upski... Read Full Bio
Comments
(1)
R
a year ago
Report Abuse
Reply to Rohan Yemul