Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why protected and private attributes are accessible by same class rather than by the same object?

For example, we have the class Man

If Man.age is protected, then I don't see why chuckNorris (instance of class Man) can change the protected/private attribute age of the object jackBauer (another instance of class Man). He shouldn't be able to do that (IMO).

In my mind, the value of a protected/private attribute is supposed to belong only to the object itself, not the class...

I need some explanation I think, I'm confused.

like image 519
Matthieu Napoli Avatar asked Dec 16 '25 22:12

Matthieu Napoli


1 Answers

Matthieu is right. cuckNorris can do jackBauer.age

But there is no problem on that. If you are referencing Man instance attributes inside Man, that means you are coding Man class, so you know what you are doing.

The problem would be if you pass me that Man class and I could access the Man attributes with out knowing how Man class is coded.

Setters and getters may be doing some business logic that I don't know and I don't need to know. But the one who coded Mam does know.

like image 150
David Ramentol Avatar answered Dec 19 '25 15:12

David Ramentol



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!