What are the get and set methods in Java?
The get and set methods are a part of encapsulation. Let’s first take a look at encapsulation.
Encapsulation
Encapsulation is the process of adding code and data into a single unit. In simple words, different materials are added to make a capsule, which is the same case as encapsulation. Moreover, encapsulation is used to hide sensitive data from the users. A class is an example of encapsulation. You can make all members of the class private (members with sensitive data).
The private member/variables can only be accessed if you work within the specific class. Outside the class, you will need the public set and get methods to update and access the value of the private variable.
-
Set: Sets the value of the private variable. -
Get: Returns the value of the private variable.
Code
public class Student{private Number rollNo; //you can't access this varible outside the Student Class}//setterpublic void setRollNo(number id){rollNo = id;}//getterpublic string getRollNo(){return rollNo;}
public class Test{Student x = new Student();x.rollNo = 22110001; // errorSystem.out.println(x.rollNo); // error}
We can see in the code above that if we assign a value to the private variable outside the class in which it is declared, we get an error. if the variable rollNo was public instead of private, our code would give the following output:
22110001
How to use get and set
Let’s use the getter and setter functions above to set and get our desired value.
public class Test{Student x = new Student();x.setRollNo(22110001); // assign rollNo variable the value of 22110001System.out.println(x.getRollNo()); // prints 22110001}
Advantages of the get and set methods
-
Control over data: You can set specific conditions within your
setterfunction; for instance, if you’ve coded in a way that thesetterfunction won’t store negative numbers. -
Flexibility: The programmer can change a specific part of the code without affecting the rest of it.
-
Privacy: The
setandgetmethods encourage users to privatize sensitive data.