0

I am working in an OO-Environment and am just having conceptual discussions with colleagues. Suppose you have two classes ("A" and "B") with no common ancestors, and B needs to access information from A. It can do that via fields or getters. The dilemma is that these would have to be declared "public" and consequently be visible to the whole world. Since "private" visibility is not possible (completely different positions in the class-tree due to different purposes), they have been implemented as public.

But I'm wondering if there is a concept (in any OO-Language) which would allow to control that these fields should only be visible to B and noone else?

MBaas
  • 7,248
  • 6
  • 44
  • 61

2 Answers2

2

C++ has Friend class and Friend function

In Java or similar, if you can modify both classes, use the Visitor pattern.

charlie
  • 1,478
  • 10
  • 20
  • Thank you - friendship looks exactly like the concept I was looking for :) – MBaas Aug 18 '16 at 09:40
  • This answer talks about sharing private data in a 'friend' type way in Java..using classes `A` and `B` :): http://stackoverflow.com/questions/14226228/implementation-of-friend-concept-in-java – jmrah Aug 18 '16 at 16:29
  • @jrahhali: Yes, and in fact, it uses the Visitor pattern, or a variation of it. – charlie Aug 18 '16 at 17:06
0

In java you can declare protected and package private fields/methods. Where protected fields/methods are accesible to classes in the same package, and to extending classes. Package private fields/methods are only accesible for classes in the same package.

So this way you cant specify one class which should only have acces, but you can limmit the acces well enough to accomplish the same effect in applications/libraries.

Note that java also provides mechanisms to prohibit acces more robust by setting acces and securityRules. It can even prevent reflection (a common way to acces normally unaccesible fields/methods in java). But it might not be the mechanism you are looking for, since it isnt really a base concept.

n247s
  • 1,898
  • 1
  • 12
  • 30