Home »
Java programming language
How to make a read-only class in Java?
Here, we are going to learn that can we make read-only class in Java? If yes, then how to make Read-only class in Java?
By Preeti Jain Last updated : March 23, 2024
The question is that "can we make a read-only class in Java?"
The answer is: "Yes, we can make a read-only in java."
Defining read-only class in Java
Now, we will see in few steps, how to make Read-only class and the various steps in given below:
We can make a class read-only by making all of the data members private.
Please note:
- If we make a class read-only, then we can’t modify the properties or data members value of the class.
- If we make a class read-only, then we can only read the properties or data members value of the class.
- The read-only class will contain only getter methods which return the value of the private properties to the main() function.
- The read-only class can contain setter methods if we want to modify the value of the private properties after reading because there is our choice to keep setter method in the class but as per based on the concepts we should not contain.
Now, we will see the objective of the getter method, why it is required?
Few points need to remember about getter methods are given below:
- As we know that "private" data member of the class is accessible in the same class only.
- Let suppose we want to access "private" data member of the class in outside class. So, in that case, we need to declare public "getter" methods.
- The objective of the getter method is used to view the private variable values.
Syntax to making a read-only class in Java
public returntype getDataMember_Name();
In the Getter method, it is not mandatory the same data member name after get, but it is convenient for our understanding that we should consider the same name as the data member after get.
There are few advantages of getter methods are given below:
- Hiding the internal representation of the private data member.
- Getter methods provide access level hierarchy.
- This method adds additional functionality easily later.
- This class allows getter methods to be passed around as lambda expressions rather than values.
- The private data member is accessible from outside the class with the help of getter methods.
Example to make a read-only class in Java
// Java program to demonstrate the example of
// making Read-only class in Java
public class Weeks {
// Private Data Member Declaration
private String days = "7 days";
// Defining Getter method to return the value of
// private properties.
public String getDays() {
return days;
}
public static void main(String[] args) {
// Weeks object instanstiation
Weeks w = new Weeks();
// Get the value of the private member
String result = w.getDays();
// Display the value of the private properties
System.out.println("Days in a Week:" + " " + result);
}
}
Output
Days in a Week: 7 days