How do getters and setters protect the data of a java class? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How do getters and setters protect the data of a java class?

When using private attributes with public getters and setters; the class data can be accessed using these getters and setters. What is the point of having them?

5th Apr 2018, 5:38 PM
knave
knave - avatar
3 Answers
0
The answer is in your question. The point in having them is the fact that private variables in a class cannot be accessed (or modified) from outside the class. So getters allow us to access them and setters allow us to change them from outside the class where they were declared. This link gives more information about access modifiers. It should be helpful. https://www.javatpoint.com/access-modifiers
5th Apr 2018, 5:41 PM
cyk
cyk - avatar
0
So, instead of having private attributes and public getters and setters; why can't we use public attributes in the first place?
5th Apr 2018, 5:45 PM
knave
knave - avatar
0
The variables are declared with the access modifier private so that they can be hidden from other classes and not be accessible directly. This has to do with the principle of encapsulation which is very important in Object Oriented Programming in Java. Please check out this link. Jakob Marley gives a very good explanation of this concept. The other answer in the thread can help you too. https://www.sololearn.com/Discuss/1128076/?ref=app
5th Apr 2018, 5:50 PM
cyk
cyk - avatar