When will I use package-private in Java?

I like access control in any language, but I find that in Java I almost never (never) used a package-private access modifier (or lack thereof).

I understand that inner classes can be private , protected or package-private , but outer classes can only be package-private or public . Why can the outer class be package-private but not protected ? What is the advantage of restricting classes / methods / fields that the entire package should see, but not subclasses?

+6
source share
2 answers

I use package-private classes and methods when I want to hide implementation details from users (and other classes) outside the package.

For example, if I have an interface and a factory class that creates instances of this interface, I may have an implementation class as a separate file, but mark it with private-package so that others cannot use it and it will not interfere with JavaDoc (if javadoc is configured to publish only).

If you seal your jar file, private-private methods can also help limit access to these methods. If the method is public or protected, subclasses can still see and call this method, even if it is in another package. (Unsealed banks allow someone to create classes in your packages so that they gain access to private or secure methods)

+13
source

In many cases, peer classes in the same package have the same author, so he knows about the internal way these classes work, or, in other words, he knows about the encapsulated logic of these classes. In this way, he can verify that the batch-private calls between classes correspond to the encapsulated logic of an accessible class and that these calls do not violate anything.

These direct calls are often useful for optimization and to reduce the amount of source code.

For the part of the question why outer classes can be private but not secure, I have no answer.

+2
source

Source: https://habr.com/ru/post/952289/


All Articles