I'm confused because all I keep hearing is that Private variables
in Java are supposed to protect the code or the variable. But if anybody has access to the code, then it makes no difference if it is private, they can still change it. So how is it considered protected when anybody who has access to the code can change it.
相关问题
- Delete Messages from a Topic in Apache Kafka
- Jackson Deserialization not calling deserialize on
- How to maintain order of key-value in DataFrame sa
- StackExchange API - Deserialize Date in JSON Respo
- Difference between Types.INTEGER and Types.NULL in
Variables are private to protect the state of your objects - in object-oriented programming terms, this is called encapsulation.
Here's a very simple example. Imagine that we have a Person class, and a Person has an age that is calculated based on the year in which they were born.
In another class somewhere, we have this... and if age was public, we could really mess up the state of our object by changing it without updating the year of birth.
By encapsulating the age variable, it's safe from unexpected changes and our class can manage its own state. Anyone who uses our class doesn't have to care about calculating a person's age, because that's encapsulated within our class.