What are Packages in Java?
A package as the name suggests is a pack or collection of classes, interfaces and other packages in Java. Packages are used to organize classes and interfaces in Java. We can categorize packages in java into two types, namely:
- Built-in packages
- User defined packages
Built – in packages
The Java API is a library of prewritten classes, which are included in the JDK (Java
Development Kit) and are free to use. You just need to use the keyword import to use a
package or any particular class of a package for that matter. There are a bunch of
predefined packages in the API library like, java.util, java.io.*,
java.lang.*.
Let us break down and visualize an example of importing a package in java.
This built – in package is used to take input from the user.
Here java is the top level package, followed by util, which is a
sub-package. And finally, Scanner is a class which is present in the sub-package
util.
User – defined packages
When we want to use a certain class multiple number of times in different programs, we can
create a package and import it as and when required. Let us look at an example to
understand
it better.
Initially, we will create a class named Calculator inside a package called
calculation.
To create a class inside a package, declare the package name in the first line of your Java
program. A class can have only one package declaration. So, in this case,
Calculator.java
file will be created inside a package calculation.
Now that we have created a package called calculation, we can import this package and use it in another different class.
Output
Let us look at the output of the above example code.
Here the user – defined package calculation is imported and using its class Calculator we can implement the functions used inside that class, namely add(). In the above program using the statement, import calculation.Calculator, we can import only the Calculator class of the package calculation. However, if we have several classes inside the package calculation, and we want to import all of them, then we need to use the following statement to do that,
Summary
There are two types of packages in java, Built – in package and User – defined package. Built – in packages comes with prewritten classes and interfaces in the JDK, whereas User – defined packages gives flexibility to the user to define his/her own package and use it in other classes as and when required.