Ok, let’s leave the debate of whether friendship breaks encapsulation, and actually try elegantly come up with a coherent design. It is a two fold function:
1) General question on how to implement:
public class A { friend class B; }
2) Why do I need this functionality? Some of my classes implement Serializable interface. However, I want to make Serializable methods protected in the Derived class so that I don’t expose them to a client (as well as in the documentation — javadoc). However, internal classes should be able to access them. What is the General way to solve this problem in java?
Note: I am using friendship as defined in the current C++ standard.
Thanks
The general solution is to make the methods package-private (which is the default protection level in Java). That way any code in the same package can access them, but not external code.
Java does not allow arbitrary sharing of methods with specific external classes.
EDIT: Protected members are actually less private than package-private. If you have protected members, you can access them from derived classes outside your package, and from any class inside the package. So that may be a solution to your problem – derive the class in another class in the package you want to export to.
Generally, Java considers the package as the main module of encapsulation. The public/protected interface is for classes outside the package, and the default protection level allows access within the package.