Is there an equivalent to C++'s "friend class" in Java?
- by Ricket
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.
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?