+ 3

How are getters and setters used to protect data.

I look at it as used to set and access the data please help me out .

5th Dec 2016, 9:12 AM
Ntirpang Louis
Ntirpang Louis - avatar
2 Respostas
+ 6
Because atributes are privated. Let's see this: class Person{ private String name; public void setName(string name){ if(name.lenght >3) this.name = name; } public String getName(){ return name; } } // Person p1 = new Person(); p1.name = "zzz"; // wich would return error, you cannot access outside the class, because its privated. So, instead of that you need to use the Setter of the name, wich controls the name lenght, so don't insert any garbage value. (Still, you can make more complex checking)
5th Dec 2016, 9:19 AM
Nahuel
Nahuel - avatar
+ 1
I wish to add on top of naguel overjero's comment, I just had a lecture regarding this. by setting the variable it self as private, you cannot directly edit the variable in the main method directly, you'll have to enter it via another method. using a method to assign a value will allow you to add more features such as checking the input is valid and also later on it allows for standarised assignment and retrieval of variables values. Lets say you have a clock object, its attributes are minutes and hours if the user states clock.minutes = 80 and the attribute of minutes isnt private, then the clock would show 80 minutes. if you use a method to set the minutes you can force the user to enter a number between 0-59.
22nd Dec 2016, 12:15 PM
Amit Goldstein
Amit Goldstein - avatar