As the number of classes implemented for the program grows, remembering all the functionality and methods becomes more difficult.
What helps is naming the classes in a sensible manner and planning them so that each class has one clear responsibility.
In addition to these measures, it's wise to divide the classes into packages. Classes in one package might share functionality, purpose, or some other logical property.
Packages are practically directories in which the source code files are organised.
The package of a class (the package in which the class is stored) is noted at the beginning of the source code file with the statement package *name-of-package*;
. Below, the class Program is in the package library
.
package library;
public class Program {
public static void main(String[] args) {
System.out.println("Hello packageworld!");
}
}
Every package, including the default package, may contain other packages.
For instance, in the package definition package library.domain
the package domain
is inside the package library
. The word domain
is often used to refer to the storage space of the classes that represent the concepts of theproblem domain.
package library.domain;
public class Book {
private String name;
public Book(String name) {
this.name = name;
}
public String getName() {
return this.name;
}
}
A class can access classes inside a package by using the import
statement. The class Book
in the package library.domain
is made available for use with the statement import library.domain.Book;
. The import statements that are used to import classes are placed in the source code file after the package definition.
package library;
import library.domain.Book;
public class Program {
public static void main(String[] args) {
Book book = new Book("the ABCs of packages!");
System.out.println("Hello packageworld: " + book.getName());
}
}
The project directory src/main/java
contains the source code files of the program.
If the package of a class is library, that class is stored inside the src/main/java/libary
folder of the source code directory.
If the access modifier is missing, the methods and variables are only visible inside the same package. We call this the default or package modifier.
The classes that represent concepts of the problem domain are often placed inside a package called domain
.
The application logic is typically kept separate from the classes that represents concepts of the problem domain.