Can someone try to explain to me in simpler form on how data hiding works, where and when to use it?? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 2

Can someone try to explain to me in simpler form on how data hiding works, where and when to use it??

Guys I have a little bit of knowledge under OOP, but the problem comes to understand the concept of data hiding.

25th Dec 2018, 8:37 AM
Tumelo Diale
Tumelo Diale - avatar
3 Answers
+ 3
Thanks HonFu, Taste and alpha5and5... I really appreciate it
25th Dec 2018, 10:51 AM
Tumelo Diale
Tumelo Diale - avatar
+ 2
In OOP ? Its a concept where an instance variable cant be access and alter directly from outside its own object. Think that its a state that cant be alter without any procedure. for example class GameCharacter{ public int hp=100; public boolean dead=false; } Here you cant simply change state "dead" to true without any procedure like take damage or hp drop to 0. Thats why we need to hide those data. And provide an interface for outside entity to alter them with defined logic. class GameCharacter{ private int hp=100; private boolean dead=false; // by using private modifier we can hide the data // We also provide public method, so it can be access from outside the class // but still following the procedure public int takeDamage(int damage){ this.hp-=damage; if(this.hp <= 0) dead=true; return this.hp; } public boolean isDead(){ return dead; } }
25th Dec 2018, 9:48 AM
Taste
Taste - avatar
+ 2
Take for example the built-in type 'list'. Usually we don't have to care how exactly it works; we know how to create a list, how to append, extend, pop, insert... and that's sufficient. Basically it's like a radio. All the electronics is under a case and we have a few buttons to use. Convenient, right? So we want to have our classes that way. Everything messy is hidden inside and the stored data can only be accessed by designated methods that take care of the proper formatting. What's left is as easy to use as a radio with buttons.
25th Dec 2018, 10:06 AM
HonFu
HonFu - avatar