Michael Cordingley
Michael Cordingley

Reputation: 1525

Visibility of Protected/Private Properties from Other Instances of Same Class

The basic rules of inheritance and visibility go as follows:

Somewhat less obvious are the rules for accessing these properties from another instance of the same class, though it is spelled out clearly in the documentation:

This happens because the object has access to the class spec. It seems to be due to a quirk of implementation in the language, albeit one that we can rely on. What I'm curious about is the rules of visibility from other object instances both up and down the inheritance chain. What I expect is:

Is this right?

Upvotes: 2

Views: 579

Answers (2)

Fabian Schmengler
Fabian Schmengler

Reputation: 24551

Not entirely. It's right that the rules are only based on classes, and it does not matter if it is the same instance or another instance and that was basically your question.

However, you made a mistake about protected in general. From the documentation:

Members declared protected can be accessed only within the class itself and by inherited and parent classes

(highlight added)

So, the following statements are wrong:

  1. Accessing protected members from a superclass is not OK.

  2. Accessing protected members from another instance of a superclass is not OK.

Upvotes: 2

Barmar
Barmar

Reputation: 780724

Yes, it's right.

The visibility rules are based only on classes, instances have no impact. So if a class has access to a particular member in the same instance, it also has access to that member in other instances of that class.

It's not a quirk, it's a deliberate design choice, similar to many other OO languages (I think the rules are essentially the same in C++, for instance). Once you grant that a class method is allowed to know about the implementation details of that class or some related class, it doesn't matter whether the instance it's dealing with is the one it was called on or some other instance of the class.

Upvotes: 3

Related Questions