Why is this an issue?

Java packages serve two purposes:

  1. Structure — Packages give a structure to the set of classes of your project. It is a bad practice to put all classes flat into the source directory of a project without a package structure. A structure helps to mentally break down a project into smaller parts, simplifying readers' understanding of how components are connected and how they interact.
  2. Avoiding name clashes — a class part of the default package if no explicit package name is specified. This can easily cause name collisions when other projects define a class of the same name.

When no package is explicitly specified for the classes in your project, this makes the project harder to understand and may cause name collisions with other projects. Also, classes located in the default package not be accessed from classes within named packages since Java 1.4.

How to fix it

Move your class to a package directory and explicitly state the package’s name at the top of the class. If your project does not have a package structure, think of a structure that fits your needs. The package names should be unique to your project. You can find some best practices when choosing package names in the Ressources section below.

Code examples

Noncompliant code example

public class MyClass { /* ... */ } // Noncompliant, no package spacified

Compliant solution

package org.example; // Compliant

public class MyClass{ /* ... */ }

Resources

Articles & blog posts