Home >Backend Development >C++ >How Can We Mimic C 's `friend` Functionality in Java?
Mimicking C 's 'friend' Concept in Java
In object-oriented programming, the 'friend' concept allows classes in different packages to access each other's non-public members. While Java lacks an explicit 'friend' mechanism, there is a clever workaround to achieve similar functionality.
Consider two classes, Romeo and Juliet, belonging to different packages. To allow Romeo to access non-public methods of Juliet, follow these steps:
This technique allows Romeo to access Juliet's non-public methods without making it a subclass of Juliet. By passing a unique token, it ensures that only Romeo can call those methods, replicating the behavior of the C 'friend' concept.
The above is the detailed content of How Can We Mimic C 's `friend` Functionality in Java?. For more information, please follow other related articles on the PHP Chinese website!