+ 3

Encapsulation- Help me out please

Encapsulation is basically hiding data correct? like hiding variables and only being able to access those variables with methods right? but why is encapsulation important? When im coding, when does the thought " oh let me use encapsulation here " happen? Do you use encapsulation for safety reasons? and if so who am i keeping my program safe from? is it hackers? Can someone give me a real life scenario where you would use encapsulation please. (ps ; i searched the database on sololearn for an explanation but couldnt find one that answered my questions properly.)

26th Jul 2017, 4:07 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
3 Answers
+ 6
yes encapsulation is for protecting not hiding but protecting data and variables from unwanted edits. there are many ways to do that. you will probably see in lessons. let me explain why: mostly best given reason is bank accounts ! you will probably never want any user go edit their money in their account. so you encapsulate that variable so they can increase or decrease that variable with only but only the way you let them programaticly with withdraw or deposit functions. so logic here is not hiding it is protecting.because user probably want to see that variable. or another example from game you encapsulate user health or life data they can see it but they can not change it with your special functions which increase health/life points while some other functions reducing life points and health points most used functions are get () and set ()
26th Jul 2017, 4:24 PM
Melih Melik Sonmez
Melih Melik Sonmez - avatar
+ 1
Thank you, your explanation was on point!
26th Jul 2017, 4:33 PM
Mogammad Shameer Losper
Mogammad Shameer Losper - avatar
+ 1
encapsulation is combining properties and method related to an object and protect it.
12th Aug 2017, 6:15 AM
Ankur Singh
Ankur Singh - avatar