Site icon TestingDocs.com

Java Packages

Overview

This tutorial will teach you Java packages, how to create and some of the advantages of using them.

What is a Package?

Java Package is a collection of related classes, interfaces, sub-packages, etc. Large projects often have many classes. Packages allow us to group and organize related classes into a directory/folder. A Package can be defined as a group of related types (classes, interfaces, annotations, etc ) providing access protection and namespace management.

Packages are used in Java in order to prevent naming conflicts, control access, to make the management of classes, interfaces, annotations, etc easier. It is easy to locate a class in a project that is organized and uses packages.

Types of Java Packages

https://www.testingdocs.com/types-of-java-packages/

Creating a Package

Let’s see how to create a package using Eclipse IDE. Note that we can also create from the command line and using windows explorer. However, we will concentrate on using IDE as this is fast and most useful while developing automation.

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 the package name and hit the Finish button.

 

Advantages of Java Packages

Programmers can define their own packages to bundle groups 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. The package creates a new namespace so 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.

Example:

package com.testingdocs.javaautomation;

The import keyword is used to access the package from outside.

Example:

import org.openqa.selenium.firefox.FirefoxDriver;

Java Tutorials

Java Tutorial on this website:

https://www.testingdocs.com/java-tutorial/

For more information on Java, visit the official website :

https://www.oracle.com/java/

Exit mobile version