0
access specifiers
If we are specifying an attribute in private, why would we want to create another public function to return its value?
5 Respuestas
+ 2
Thank you bro Avinesh
+ 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.
+ 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.
+ 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.
+ 2
Hoo... Visual description of guard huh? Good for remembering 😁 thanks HonFu