Pros and cons of package private classes in Java?

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.

Leave a Comment