I was wondering why Java has been designed without the friend
directive 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.
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.
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.
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.
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.
Here are a few reasons off the top of my head:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With