Why friend directive is missing in Java?

后端 未结 8 1455
被撕碎了的回忆
被撕碎了的回忆 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:57

    In my opinion some kind of friend feature (not necessarily very similar to C++'s) would be very helpful in some situations in Java. Currently we have package private/default access hacks to allow collaboration between tightly coupled classes in the same package (String and StringBuffer for instance), but this opens the private implementation interface up to the whole package. Between packages we have evil reflection hacks which causes a whole host of problems.

    There is a bit of an additional complication in does this in Java. C++ ignores access restrictions whilst resolving function overloads (and similar) - if a program compiles #define private public shouldn't do anything. Java (mostly) discards non-accessible members. If friendship needs to be taken into account then the resolution is more complicated and less obvious.

提交回复
热议问题