Why friend directive is missing in Java?

后端 未结 8 1440
被撕碎了的回忆
被撕碎了的回忆 2020-12-03 14:23

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

8条回答
  •  死守一世寂寞
    2020-12-03 14:42

    Completely agree with spaceghost's statement in his answer

    Contrary to popular opinion, here are many cases, in particular for infrastructure capabilities, where friend access leads to BETTER design, not worse design.

    My example is simple - if a class A has to provide a special "friend" interface to class B in java we have to place them into the same package. No exceptions. In that case if A is a friend of B and B is a friend of C, A has to be a friend of C which isn't always true. This "friendship transitivity" breaks encapsulation more then any problems which C++ friendship could lead to.

提交回复
热议问题