C++-like friend class mechanism in Java

前端 未结 4 1676
天涯浪人
天涯浪人 2021-01-12 21:40

Do you know how can I make an object changeable only inside a special class? In this example I want the object PrivateObject to be only changable (incrementable) inside the

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-12 22:19

    Java does not have any language feature equivalent of C++'s friend keyword. However , there are number of application-level alternatives :

    1. Declare the increment() method of the PrivateObject class as package- private and define Box in the same package.

    OR

    2.Let the calling code pass a token into increment() - inside this method check if this token is indeed coming from Box class and allow or disallow.

    The idea is to keep the coupling between PrivateObject and Box class manageable.

提交回复
热议问题