In this post, we will discuss working with Packages in java.
What is a Package?
A package is a namespace that organizes a set of related classes and interfaces. Also, packages are used in Java in order to prevent naming conflicts, to control access, to make the management of classes, interfaces, annotations etc easier.
A Package can be defined as a group of related types (classes, interfaces, annotations etc ) providing access protection and namespace management. In addition, an example of In-built package in Java is shown below:
java.lang : the fundamental classes ( no need to import these classes explicitly )
User defined packages
User defined packages are created by us for our own purpose. Also, we need to import the classes in user defined packages to make use of them. In this post, i will show how to create package using Eclipse IDE. Note that we can also create from command line and using windows explorer. However , we will concentrate using IDE as this is fast and most useful while developing automation.
Creating a Package:
A folder with the given package name is created in the specified destination, and the compiled class files will be placed in that folder.
Right click on Project >> New > Package as shown in the below picture:
Enter package name and hit Finish button.
Advantages of packages:
Programmers can define their own packages to bundle group of classes/interfaces, etc. We need to group related classes in a package as a good practice. As a result, others can easily determine that the classes, interfaces, enumerations, and annotations are related. Furthermore, package creates a new namespace there won’t be any name conflicts with names in other packages. Consequently, using packages, it is easier to provide access control and it is also easier to locate the related classes.
Using and Importing a package
While creating a package, you should choose a name for the package. Also, include a package statement along with that name at the top of every source file that contains the classes, interfaces, etc that you want to include in the package. Furthermore, the package statement should be the first line in the source file. There can be only one package statement in each source file, and it applies to all types in the file.
The import keyword is used to access the package from outside.