Why do people use private variables?

Why do people use private variables?

Private variables help prevent people from depending on certain parts of your code. For example, say you want to implement some data structure. You want users of your data structure to not care how you implemented it, but rather just use the implementation through your well defined interface.

Why should Fields be private?

In Summary private keyword in java allows most restrictive access to variables and methods and offer strongest form of Encapsulation. private members are not accessible outside the class and private method can not be overridden.

Can a variable be private in a public class?

Variables should be private inside a public class, as we don’t want to allow people to see how this information is stored or to be able to edit information without authorisation. So now, I’ll edit the Person class to declare the two Strings private and add get and set methods, like so:

Why do we need private variables in Java?

Hence, private variables ensure that the corresponding variable remains in the defining class only. If you need to change it, the change is local to the class itself. In traditional lanugages like C++ or Java, you usually make everything private and only accessible by corresponding getters and setters. No need to decide much really.

Why do we need private variables in OOP?

All your implementation details should be private, and the public part should be a small, concise, well-defined interface for using your class. The keyword here is Encapsulation. In OOP you want to use private variables in order to enforce proper encapsulation of your objects/classes.

When do we need to make things private?

So, as to when you should make things private: I’d say make everything private by default, and then expose only those parts that absolutely have to be public. The more you can make private, the better. Private variables help prevent people from depending on certain parts of your code. For example, say you want to implement some data structure.