Possible Duplicates:
‘Friends’ equivalent for Java?
Is there a way to simulate the C++ ‘friend’ concept in Java?
In C++ there is a concept of a “friend”, which has access to a class’s private variables and functions. So if you have:
class Foo {
friend class Bar;
private:
int x;
}
then any instance of the class Bar can modify any Foo instance’s x member, despite it being private, because Bar is a friend of Foo.
Now I have a situation in Java where this functionality would come in handy, but of course it doesn’t exist in Java.
There are three classes: Database, Modifier, Viewer. The Database is just a collection of variables (like a struct). Modifier should be “friends” with Database; that is, it should be able to read and write its variables directly. But Viewer should only be able to read Database’s variables.
How is this best implemented? Is there a good way to enforce Viewer’s read-only access of Database?
There are varying opinions on how pure you should be, but to me you shouldn’t give anyone access to any fields. Use getters and setters.
If you need to segregate who can read and who can write, you can throw interfaces into the mix. Define an interface with just the getters and you can restrict your viewer to read only.
Robert Harvey added a comment that points to other options, like using a different access modifier for class or package level access.