Package Naming Conversion in Java
In Java, package plays an important role in preventing naming conflicts, controlling access, and making searching and usage of classes, enumeration, interfaces, and annotation easier.
In order to group classes, interfaces, and sub-packages that are related to each other, we use packages. By using packages:
Now, let's understand how we can create packages and their naming conventions one by one.
Creating a Package
We use the package keyword as a very first line of code in the file for creating a package in Java4sz. We create a package by adding the package keyword as the very first line of code in a file. The syntax of creating a package in Java is as follows:
We highly recommend you to add only a unique type in a package. If we don't place the defined type in a package, they will be placed in the default or unnamed package.
These are the following disadvantages of putting types into unnamed packages:
So, we should have to avoid the use of unnamed or default packages in RWA(Real World Applications). To learn more about packages, go through the following link:
For avoiding unwanted package names, we have some following naming conventions which we use in creating a package.
In order to define a package name based on an organization, we'll first reverse the company URL. After that, we define it by the company and include division names and project names.
For example, if we want to create a package out of www.javatpoint.com, we will reserve it in the following way:
If we want to define a sub-package of the com.javatpoint, we will do it in the following way:
How to use package members?
First, we define a class Test in a sub-package name examples:
Now, if we want to use Test class from outside the package, we will import it in the following way:
In Java, we have some pre-defined classes and package available. We import the classes available in the pre-defined packages in the same way as we import classes in our own packages.
If we want to import ArrayList and List classes from the util package, we will import it in the following way:
Let's take an example to understand how we can create a package, run it and compile it using Java.