a shot of dev knowledge

RELATED TAGS

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
}
//setter
public void setRollNo(number id)
{
  rollNo = id;
}
//getter
public string getRollNo()
{
  return rollNo;
}
The set method takes in the parameter and assigns it to variable rollNo. The get method returns the value of variable rollNo.
public class Test
{
      Student x = new Student();
      x.rollNo = 22110001;  // error
      System.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 22110001
      System.out.println(x.getRollNo()); // prints 22110001
}
Now, the output of the code will be 22110001.

Advantages of the get and set methods

  • Control over data: You can set specific conditions within your setter function; for instance, if you’ve coded in a way that the setter function won’t store negative numbers.

  • Flexibility: The programmer can change a specific part of the code without affecting the rest of it.

  • Privacy: The set and get methods encourage users to privatize sensitive data.

RELATED TAGS

RELATED COURSES

View all Courses

Keep Exploring