I just...am not entirely sure I understand encapsulation. Maybe it might have to do with the fact that I'm still learning programming in a class and haven't made any like..REAL world programs to be used by other people, but I just don't understand what it's trying to accomplish. I understand that its restricting access to some of a class' members and functions. But like..restricting it from who? I've seen several examples where they have a private data member, but they have public get or set methods that allow the data member to be manipulated anyway. So how was anything restricted or hidden?
My book says the following:
" Encapsulation provides two important advantages:
I guess I'm confused about the words they are using. How, or can someone give me an example, of how user code could possibly corrupt the state of an object?
I know my question is kind of all over the place but so is my mind when it comes to thinking about encapsulation so I'm having a difficulty encapsulating all my thoughts about it (..lol)
My favorite example of encapsulation is driving a car.
The typical driver knows how to make a car go forward by turning on the ignition, and stepping on the gas pedal. They don't need to know anything about internal engine combustions in order to get to work every morning.
The gas pedal exposes a very simple interface for operating a very complex machine. Meaning, the really complicated internal details are encapsulated from the driver.
Now, in terms of code, say you want to use a Map
of some kind, but you don't know how to write generic hash functions for your keys, or how to implement any of the other underlying details.
In Java you can simply use a HashMap
, without having to worry about what the standard library is doing underneath. These details are encapsulated from the user.