Pros and cons of package private classes in Java?
I am learning Java recently, and I came across the notion of package-private
classes, which is the default if we don't specify anything. But then I realized:
I seldom see the use of package-private class. Is there a reason for this, e.g., it has serious drawbacks, it is redundant, or simply I am not reading enough? Are there strong arguments for/against its usage?
If it is really not useful in most cases, why would it be the default?
In what situation should we use package-private in the real world? I.e., when would it become irreplaceable?
In other words, what are the major pros and cons of the default package-private modifier?
Solution 1:
The short answer is - it's a slightly wider form of private.
I'll assume that you're familiar with the distinction between public
and private
, and why it's generally good practice to make methods and variables private
if they're going to be used solely internally to the class in question.
Well, as an extension to that - if you're thinking about creating your software in a modular way, you might think about a public interface to your module, which will have multiple classes inside it collaborating between themselves. In this context it makes perfect sense to make methods public
if they're going to be called by consumers; private
if they're internal to a class; and package private
if they're used to call between classes in this module, i.e. it's an implementation detail of your module (as seen by public callers) but spans several classes.
This is seldom used in practice, because the package system turns out to not be so useful for this sort of thing. You'd have to dump all of the classes for a given module into exactly the same package, which for anything non-trivial is going to get a bit unwieldy. So the idea is great - make a method accessible to just a handful of "nearby" classes, as a slightly wider private
- but the restrictions on how you define that set of classes means it's rarely used/useful.
Solution 2:
One nice thing about package-private is that you can use it to give access to methods you would otherwise consider private to unit test classes. The downside of course being that other classes in the package could call it when they really shouldn't.