Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why friend directive is missing in Java?

I was wondering why Java has been designed without the frienddirective that is available in C++ to allow finer control over which methods and instance variables are available from outside the package in which a class has been defined.

I don't see any practical reason nor any specific drawback, it seems just a design issue but something that wouldn't create any problem if added to the language.

like image 991
Jack Avatar asked Jan 10 '11 14:01

Jack


People also ask

Why There Is No 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.

Why friend function is not inherited?

In C++, the friendship is not inherited. It means that, if one parent class has some friend functions, then the child class will not get them as friend.

Is there friend keyword in Java?

Friend Concept in Java🎯 Java does not have the friend keyword like c++, which is used to access the non-public members of a class. Nevertheless, we can achieve this functionality.

Where is friend function declared?

A friend function is declared inside the class with a friend keyword preceding as shown below. class className{ …… friend returnType functionName(arg list); }; As shown above, the friend function is declared inside the class whose private and protected data members are to be accessed.


2 Answers

Here are a few reasons off the top of my head:

  • friend is not required. It is convenient, but not required
  • friend supports bad design. If one class requires friend access to another, you're doing it wrong. (see above, convenient, not required).
  • friend breaks encapsulation. Basically, all my privates are belong to me, and that guy over there (my friend).
like image 89
DwB Avatar answered Oct 05 '22 23:10

DwB


In general i think it was because of the added cognitive complexity and low number of cases in which it creates an improvement.

I would say that the extremely huge number of lines of java in production at this moment can attest that the friend keyword is not really a big loss :).

Please see @dwb's answer for some more specific reasons.

like image 27
Mihai Toader Avatar answered Oct 05 '22 23:10

Mihai Toader