How to create a package in Java

A package is defined as a collection of built-in classes. Packages in Java can be classified into two types namely:

  • Built-In packages
  • User-defined packages
svg viewer

Java API provides a collection of packages to be used in Java applications called built-in packages. While developing Java applications, a programmer can create his own packages. These packages are called User Defined packages.

How to create packages

To create our own package, we have to implement the following steps:

  1. First, we create a directory as a sub-directory of bin whose name is the same as the package’s name. For example, create a directory with the name MyPack.
  2. Now, move into the new directory. Then, create a Java class whose first statement of the file should be a package statement, package MyPack;
  3. After creating the class, save it with the class-name and compile it. In this way, we can create multiple classes in the new package where each class is created as a separate Java file.
  4. After creating the package with a set of classes, move into bin directory. Now, the classes in the new package can be imported to our Java applications using the import statements, import MyPack.*;

Access specifiers in Java

Access Specifiers specify the way in which a class, an interface, or abstract class and their members are accessed. Java supports four types of access specifiers:

  1. public: Any java element that is declared as public is accessible to the members of the same class, the classes in the same directory, or the classes in another path.
  2. private: Any java element that is declared as private can be accessible to the members of the same class, only. It cannot be available for the classes that are on the same path or outside the path.
  3. protected: Any java element that is declared as protected is accessible to the same class members or to its sub-classes within the same path or outside the path.
  4. Default Access specifier: This means that a Java element is not declared as public, private, or protected. This default specifier will act as public for the same class members or other classes that are on the same path. It will act as private for the classes that are defined outside the path. And will act as protected for the derived classes of the same path and outside the path.

Free Resources