Why use private | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
- 1

Why use private

why use private in a problem why not just make everything public?

26th Jan 2017, 5:05 AM
Kaarim Saidi
Kaarim Saidi - avatar
2 Answers
+ 7
There might be some data or methods that have no reason to be accessed outside the class. It's a means of making data more manageable. For example, let's say you had a method to obtain someone's address (which would be public). You might want to break it up into smaller methods to get and validate street, ZIP, state, etc. These small methods would be private, because they're incomplete half-steps for a full action. It'd make no sense to call all of them outside the class. And its easier to use, because you only call one method to do all these actions in the right order. With data, if you have something that's calculated with a formula (ex: someone's salary), that data should be private so it cannot be modified in a way that doesn't match up with the other data (ex: salary could be made too high/low compared to number of hours worked & wage).
26th Jan 2017, 5:48 AM
Tamra
Tamra - avatar
+ 1
It's an extra safety measure.. so you dont change it accidentally.
26th Jan 2017, 5:27 AM
Nikolai Russev
Nikolai Russev - avatar