Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would you declare getters and setters method private? [duplicate]

Tags:

I saw a code where getters and setters methods are declared private. I am trying to figure out the logic behind it, and I am really having hard time to understand why would you declare them as private? That's exactly opposite of what we are trying to achieve through getters and setters.

like image 915
Vandan Patel Avatar asked Jan 24 '12 08:01

Vandan Patel


People also ask

Should setters and getters be private?

Usually you want setters/getters to be public, because that's what they are for: giving access to data, you don't want to give others direct access to because you don't want them to mess with your implementation dependent details - that's what encapsulation is about.

Why variables should be defined as private and their getters and setters as public?

The answer is it can be accessed only from within the class in which it is declared. Any private member of the class can be accessed only from within the class in which it is declared. How do you interact with a private variable from another class in Java?

What is the purpose of getter and setter methods?

Getters and setters are used to protect your data, particularly when creating classes. For each instance variable, a getter method returns its value while a setter method sets or updates its value. Given this, getters and setters are also known as accessors and mutators, respectively.

Should getters be public or private?

In general, they should be public. If they are private they can only be called from within your class and, since you already have access to the private variables within your class, are redundant. The point of them is to allow access to these variables to other, outside, objects.


1 Answers

I can think of several reasons:

  • you want to prevent future public access.

If a different programmer sees your code and wants access to a variable, but there are no setters and getters, he might think you just forgot about them, and add them themselves. However, if you declare them as private, it's a statement of intent, saying I don't want these variables to be changed or accessed from the outside.

  • you want to associate setting and getting with other actions

Say you don't want public accessors. But maybe you want a count of how many times a private variable is changed. It's easier to use a setter rather than incrementing the count every time you access that variable.

  • you want a central access point

Again, you don't want public access, but during debugging, you might want to put a breakpoint in every place a private member is changed. So instead of setting breakpoints everywhere in the class, you just set one in the accessor.

like image 79
Luchian Grigore Avatar answered Sep 22 '22 17:09

Luchian Grigore