Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

c++
java
communitycreator

Why do we use getters and setters?

Behzad Ahmad

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Encapsulation

Encapsulation is used to hide or protect sensitive data or information from all users. In order to encapsulate the data, we must declare variables/attributes of a class as private so that they can’t be accessed from outside the class. Now, if we want to read or change the values of private members outside the class, we’ll have to use the public get and set methods.

The get method is used to return the data/value. It is also known as an accessor method.

The set method is used to set or update the value/data. It is also known as a mutator method.

Following are the benefits of using getters and setters.

  • Code readability: The code is very easy to read and understand. It is also easy to look for errors in the code.

  • Data protection: The data is protected as we cannot directly access the private members/attributes of a class.

Example

Following is the basic C++ code to demonstrate the use of getters and setters:

#include <iostream>
using namespace std;
class Student
{
private:
// Private attribute
int rollNo;
public:
// Setter
void setRollNo(int id)
{
rollNo = id;
}
// Getter
int getRollNo()
{
return rollNo;
}
};
int main()
{
Student obj;
obj.setRollNo(123);
cout << obj.getRollNo();
return 0;
}

Explanation

In this example, we have a Student class with a private member variable rollNo in line 8. Since we cannot directly access rollNo outside the Student class, the public functions setRollNo and getRollNo() are used.

RELATED TAGS

c++
java
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring