In the last we talked about inheritance today we are getting into encapsulation
Encapsulation
So we have our house right. Now imagine you have a boiler room in that house the boiler controls the heating and hot water for the whole house.
You don't want just anyone walking in there and messing with it. So you lock the door.
But you still need a way to control the heating so you put a thermostat on the wall, anyone can use the thermostat but nobody can get directly to the boiler.
Thats encapsulation.
In Java you can hide the fields of a class from the outside, make them private so nothing outside that class can directly touch them
But you still provide a way to interact with them through methods. Those methods are called getters and setters. Getters let you read the value, setters let you change it.
But Why
Because direct access is dangerous. If anything in your program can just reach into a class and change its fields directly, things break in ways that are hard to track down.
Encapsulation puts you in control. You decide what can be seen, what can be changed and how.
You are the one setting the rules
That's really what encapsulation is about. You built the house, you decide which rooms are locked and which ones are open.
The thermostat is there for a reason it's a controlled way in. The more i learn Java the more i see that a lot of these concepts are really just about control and structure.
Encapsulation is probably the clearest example of that.
These are just more things i'm picking up as i go. Analogies make it stick better than any definition ever could.
Top comments (0)