Java Packages

Package Overview

Related classes and interfaces can be grouped together to classify classes and make them easier to use. This is called a package. In other words, a package is a group of similar kinds of classes or interfaces.

  • It groups classes together.
  • It prevents conflicts caused by duplicate names between classes.
  • It makes it easy to identify needed classes by classifying them by function.

Packages are a mechanism related to naming and access control. Inside a package, you can create classes that cannot be accessed by code outside that package. You can also configure class members that can be accessed by other members of the same package.

Package names are generally written in reverse order of domain names. Many Java classes and interfaces are written by many developers, classified into packages, and used by many people. If package names are chosen freely, packages with the same name may appear and cause confusion. For that reason, packages made by a company or organization are usually written in a form such as com.devkuma.tutorial, reducing duplicate package names as much as possible.

Defining a Package

A package declaration is placed at the very top of the source file. By convention, package names are written entirely in lowercase, and paths or units are separated by dots (.).

package packageName[.packageName[.packageName]...];

class ClassName { ...
package com.devkuma.tutorial;

class HelloWorld { ...

Declaring and Creating Objects with Packages

To use an object that belongs to a package, the package name must be written. This is because it becomes clear which class belongs to which package only when all of that information is written.

Therefore, an object can be declared and created in the following form.

packageName[.packageName[.packageName]...].ClassName objectVariableName = new packageName[.packageName[.packageName]...].ClassName();

In the code below, the HelloWorld object belongs to com.devkuma.tutorial, so the object variable is declared as com.devkuma.tutorial.HelloWorld, and the com.devkuma.tutorial.HelloWorld constructor is called to create the object.

com.devkuma.tutorial.HelloWorld helloWorld = new com.devkuma.tutorial.HelloWorld();