Java uses packages as it’s main way to group Classes and Interfaces together. It supports Encapsulation and Information Hiding,#ask Why?

Packages also prevent naming conflicts, as multiple classes with the same name can exist within a package, given that they exist in separate directories (folders). Packages are stored in directories.

Adding a Class to a package

Use the keyword package followed by the package directory in the first line of the class program. Java uses . to nest directories, instead of /

For example:

package shapes.simple
 
public class Circle {}

Adds the class Circle to a package stored in folder simple which is a subfolder of shapes. The full path would be: shapes/simple/Circle.java

Importing packages

Packages can be imported using Java’s import keyword. When import is used, the JVM (Java Virtual Machine) checks in an environment variable called CLASSPATH for any packages, similar to how the OS checks PATH for any executable binaries.

import shapes.simple.Circle;
 
// Use Circle class for stuff 

The above code snippet only works if shapes is in the CLASSPATH directory.

Default Package

Java implicitly creates a default package, which all classes that are in the same directory belong to.

#todo Pasted image 20240826092945

https://www.geeksforgeeks.org/packages-in-java/