Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Friends' equivalent for Java? [duplicate]

Tags:

having a little architectural trouble here.

In C++, we have the notion of 'friends,' where such friend classes can access private members.

So, I'm deving a Java app and trying to adhere to the MVC architecture. I've got a controller class that manages graph connectivity between 'map_objects.' I'd like to hide the function in the DTO 'map_objects' that actuall sets up these connectivities, by using this controller class.

(Ie, even if the controller class implements the required functionality of setting up connectivities, the 'users' can still access setter/getter functions in the the DTO directly to set them up themselves.)

Are there any design patterns or tips in this regard? (Or have I totally mucked up?)

DUPLICATE Is there a way to simulate the C++ 'friend' concept in Java?

like image 322
Alex Lim Avatar asked Dec 17 '08 23:12

Alex Lim


People also ask

Is there any friend function in Java?

friend function of a class is defined outside that class' scope but it has the right to access all private and protected members of the class. Even though the prototypes for friend functions appear in the class definition, friends are not member functions.

Is there a friend class in Java?

4) The concept of friends is not there in Java.

Why is there no friend in Java?

It's simply wrong. While it's true that friend can be used to break encapsulation, so can other features be misused. Used correctly, friend enhances encapsulation because it enables a more fine-grained access control: friend replaces use of public , not use of private .

What is a friend function in OOP?

In object-oriented programming, a friend function, that is a "friend" of a given class, is a function that is given the same access as methods to private and protected data. A friend function is declared by the class that is granting access, so friend functions are part of the class interface, like methods.


1 Answers

(Un)fortunately, there is no direct C++ friend equivalent in Java. However, the Java access level modifiers can assist you. In particular, private or package private (AKA package protected, or "default") may help.

like image 84
Julien Chastang Avatar answered Oct 08 '22 23:10

Julien Chastang