How to Create Package in Java
In Java, a package is a group of classes, interfaces, enumeration, and annotations. Java contains many pre-defined packages such as java.lang, java.io, java.net, etc. When we create any Java program the java.lang package is imported by default. We need not to write the package name at the top of the program. We can also create our own package by providing the name that we want. In this section, we will learn how to create a package in Java.
We use package for the following reasons:
Creating a Package
To create a package, follow the steps given below:
Package Naming Convention
We follow the naming convention rules to name a package. Java has some predefined packages and also allows us to create our own package. So, it is possible that a programmer can create a class with the same name as a package that already contains that type in a predefined package.
Let's take an example of the Rectangle class.
Suppose, a programmer creates a class with the name Rectangle in the package shape. The class with the same name is already present in java.awt package. The compiler allows both classes if they belong to the different packages. The fully qualified name of each class contains the package name that differentiate both Rectangle classes. Therefore, the package name of the user-defined class will be shape.Rectangle and the package name of the predefined class will be java.awt.Rectangle.
Importing a Package
If we want to use a package in Java program it is necessary to import that package at the top of the program by using the import keyword before the package name.
Let's create a calculator program in Java using the package.
Now, we are going to create the main class named Calculator. In this class, we have imported all the packages that we have created above. It includes all the classes in the Calculator class.
When we compile the above program, it creates corresponding .class files in packages named p1, p2, p3, p4, and p5, respectively.
The .class files are generated. Now, we can run the above program.
Enter your choice: 3 Enter the first number: 2 Enter the second number: 23 Product=46