+ 2

What is the need of getter and setter method?

23rd Nov 2016, 4:13 PM
somnath
somnath - avatar
9 Antworten
+ 3
Get functions to access private data and Set to assign values to it.
23rd Nov 2016, 4:28 PM
Karl T.
Karl T. - avatar
+ 2
You are only limiting direct access to variables. For example a setter can be private but does not have to. You can use your private setter only in your constructor for checking a value for specific conditions. Another kind of use is to make the setter public. Even if you think that this does make no sense, it does. Sure you are right that this is a bit weired but you just have to think of the manipulation process. By using a setter function its way more controllable how your value can be changed.
23rd Nov 2016, 4:44 PM
Andreas K
Andreas K - avatar
+ 1
it is need to prevent from driect to access Because of that, setter is private,( because a person can change the value), but getter is public, because everyone can get the value
23rd Nov 2016, 4:38 PM
Ozan Karataş
Ozan Karataş - avatar
+ 1
Andreas...is my example wrong???
25th Nov 2016, 2:38 AM
somnath
somnath - avatar
0
The concept getter and setter are needed for is called encapsulation. It is part of object-orientated programming. You need them to limit access to private attributes of classes.
23rd Nov 2016, 4:25 PM
Andreas K
Andreas K - avatar
0
I know.but I could not understand how I m limiting. methods are public
23rd Nov 2016, 4:35 PM
somnath
somnath - avatar
0
should I say...it is like... only bank will deposit money and we can access from any ATM.. if wrong..give me some practical example
24th Nov 2016, 4:38 PM
somnath
somnath - avatar
0
Here is an Example. There is a post box. This post box is public. Someone throws in a message (setter). This post box is not locked, so everyone can open it to see what the message is. The point is that you cannot access the message on a direct way. You have to know where your post box is, to throw something in or get something.
24th Nov 2016, 8:44 PM
Andreas K
Andreas K - avatar
0
your example is ok but misses the setter function as I see.
25th Nov 2016, 8:51 AM
Andreas K
Andreas K - avatar