Java / Java 21 Coding Standards Interview Questions
When should you use module-info.java for encapsulation as per coding standards?
A module-info.java is warranted once a project is distributed as a reusable library or split into independently versioned components, because the Java Platform Module System lets it declare exactly which packages are exported for external use and which remain fully internal, even to other modules on the classpath.
module com.acme.billing { requires java.sql; exports com.acme.billing.api; // com.acme.billing.internal is NOT exported - inaccessible outside the module }
This is a stronger guarantee than package-private visibility alone, which only hides members within the same package; a class in com.acme.billing.internal marked public is still fully accessible to any other package unless the module system itself refuses to export that package at all.
Standards recommend skipping modules for small internal applications where the classpath is entirely controlled by one team, since the added ceremony of declaring and maintaining requires/exports directives is not worth it unless there is a real boundary - a published API, a plugin system, or a multi-team monorepo - to enforce.
More Related questions...