Avoid the Default (Unnamed) Package

ID

java.avoid_default_package

Severity

info

Remediation Complexity

medium

Remediation Risk

low

Remediation Effort

medium

Resource

Code Smell

Language

Java

Tags

best-practice, code-style

Description

Reports source files that do not contain a package declaration but define at least one top-level type. Classes in the default (unnamed) package cannot be imported by classes in named packages, severely limiting reuse.

Rationale

The default package exists mainly for simple tutorials and throwaway scripts. In a real project, omitting the package declaration causes several problems:

  • The class cannot be referenced from any named package via an import statement.

  • Name collisions become much more likely when multiple libraries or modules use the default package.

  • Access-control assumptions (package-private visibility) become meaningless.

// Bad — no package declaration
public class MyClass {
    // cannot be imported from named packages
}

Remediation

Add a package declaration that follows the reverse-domain naming convention.

package com.example.myapp;

public class MyClass {
    // now importable from any other package
}