开发者

Who will take the role of Friend functions in java as in C++?

Who will take the role of Friend functions in java as in C++? How will it work 开发者_如何学Pythonin java ?

Thanks..


The closest thing Java has to C++ friends is the default access modifier, also known as package-protected or package-private. This allows access to members only from other classes within the same package.

This is also the best reason to place classes in the same package, rather than grouping into subpackages based on functionality.


There's no concept of a friend function in Java. Your best bet is to learn about how Java does visibility - package-private (the default) in particular may be interesting to you -- here's a quick tutorial


Chances are that your design is a little off. There really shouldn't be a need to have a friend function and that's why Java didn't include it in its language. Functions should be next to where the data it uses is located and if not then that data should be passed into the function as a parameter. In my opinion, Friend Functions go against the major ideas of OO programming. C++ tends to like to allow you to create non-OO programs even though the language fully supports the concepts that OO programming believes in.

I would consider modifying your design to put the functionality closer to where the data lives, then you really won't have this problem. However, this is not always possible especially if you are working with a legacy system. In that case, you should consider adapter classes, getters and setters, or parameters. Just my two cents.


The friend function is demerit of OOPs concept because it is used to access a class member function from the outside. That's why it has been removed from Java.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜