+ 3

I don't get how abstraction and encapsulation really hide data.

the user will have an interface (buttons or whatever) to manipulate data. He wont access the source files so how are we really protecting anything with this?

7th Nov 2016, 3:55 PM
Ramy Alayane
Ramy Alayane - avatar
2 Answers
+ 17
This isn't for the user you hide datas but for you and the programmers who are working with you. The goal of encapsulation is to prevent the mistakes you can do with your code. Let's take an example: A Human class, with a private int age = 0. So, we'll add a grow method: public void grow() { age++; } The problem if the age variable is public, it is you can change it as you want. If I want to do Human human = new Human(); human.age += 10; You can do this, but it is illogic: You can't grow by 10 like that in real life, same in programmation. So, it is better to encapsulate and create a getAge method, a setter can be also be used if you do: human.age = 200 or human.age = -1 : It doesn't exist. So, a setter can protect datas like this: public void setAge(int newAge) { if(newAge < 125 && newAge >= 0) age = newAge; } I recognize I was in same case as you when I was younger and it is a common, logic and good question ;)
7th Nov 2016, 9:13 PM
Volts
Volts - avatar
0
Thankyou very much @volts i finally get it.
7th Nov 2016, 9:45 PM
Ramy Alayane
Ramy Alayane - avatar