Packages are used to group common set of classes and interfaces in Java in an organized manner. This makes our code organized and easy to understand. As java provides huge set of class libraries, packages help to group them in such a way that, all related classes are grouped into a single package.

Packages in java

Following are the few advantages of java packages:

  • It avoids namespace collision. Different packages may use same class name without any namespace collision. A simple example is java.util.Date and java.sql.Date  classes, having same Date class.
  • Makes it easier to organize classes of a huge project, having multiple classes. As stated earlier, it organizes the project structure.
  • Packages also provides package level access control for the classes.

Following is the simple example of declaring a package:

//Package declaration:
package com.asb.test;

Importing a package:

import com.asb.*; //import all types inside a package.
import com.asb.test; //importing a particular package.

In above example, all the types inside the com.asb packages is imported using first import statement. To import types inside com.asb.test, we need to explicitly import it.

We can use static import statement to access static final fields or to access static members of a class as shown below:

import static packageName.ClassName.*; //imports all static members

import static packageName.ClassName.static_field; //imports static filed : static_field
import static packageName.ClassName.static_method; //imports static method: static_method

Also read: