0

access specifiers

If we are specifying an attribute in private, why would we want to create another public function to return its value?

4th Feb 2020, 2:06 PM
sairahul
sairahul - avatar
5 odpowiedzi
+ 2
Thank you bro Avinesh
4th Feb 2020, 2:18 PM
sairahul
sairahul - avatar
+ 4
You can imagine the public method as a *guard* for that private attribute. If the attribute was public, it could be changed in any way from anywhere in the code, it could lead to chaos. Your public method alone controls, if or how the attribute can be accessed or changed, and what exactly happens then.
4th Feb 2020, 2:34 PM
HonFu
HonFu - avatar
+ 3
Because the access specifier 'private' cannot be accessed outside the class in which it is defined. So you make use of a public function which helps you do that.
4th Feb 2020, 2:12 PM
Avinesh
Avinesh - avatar
+ 3
sairahul: You heard the term 'encapsulation', right? That's what it's about really. You make a casing that protects the data, and only define very few paths - you could also call them airlocks - how to read or change them. All for safety. It's like a casing around for example a radio. You don't want anybody to mess with the electronics, so you hide it (private), while you install a few buttons (public setter and getter methods) to safely control it.
4th Feb 2020, 3:17 PM
HonFu
HonFu - avatar
+ 2
Hoo... Visual description of guard huh? Good for remembering 😁 thanks HonFu
4th Feb 2020, 3:06 PM
sairahul
sairahul - avatar