What’s a library?
Wikipedia defines library as a collection of sources of information and similar resources, made accessible to a defined community for reference or borrowing.
Library is a place which contains tons of books and resources which we can go and access.
Packages in Java are somewhat similar.
A package in Java is a group of similar types of classes, interfaces, and sub-packages.
Packages contained inside another package are called sub–packages.
Packages allow us to maintain our code and improves efficiency by promoting reusability.
A class once written in a package can be used repeatedly, there’s no need to write the same class again.
To use the package the import Keyword is used.
import packageName.subPackageName.className;
This will import someClass from a subpackage contained in a package.
There are two types of packages:
- Built-in packages
- User-defined packages
Let’s explore both of them.
Built-in packages
Java provides many built-in packages which we can directly use in our programs.
Actually, we have been continuously using them a lot since the beginning of this course.
Let’s have a look at few frequently used packages and their use.
- java.util – This package contains classes related to time, scanner, array manipulation, data-structures, etc.
- java.io – This package contains classes required for input/output operations.
- java.lang – This package contains classes which are fundamental to the design of java language like object.
- java.awt – This package contains the common GUI elements.
If we want to import any class from the package util we write
import java.util.ClassName;
In case we want to import all the classes of a package, we write
import java.util.*;
Awesome! Now it’s time to find out what user–defined packages are and how we write them. So let’s get started.
User-defined packages
The packages created by us are known as user–defined packages.
To create a package, the keyword package is used.
package keyword is followed by name of package.
This statement comes on top of the file.
The classes declared under this statement becomes part of the package.
Let’s write a package named cartoon.
package cartoon; //a package named cartoon
That’s it.
Now, let’s write a class Tom inside this package.
package cartoon;
public class Tom{
//body
}
Awesome! We have the class Tom inside the package cartoon.
Now, if we want to access the class Tom present in the package cartoon, we can write
import cartoon.Tom;
And then go on to access the methods and variables of the class Tom like the way we usually do.
To summarize
- A package in Java is a group of similar types of classes, interfaces and sub-packages.
- To use a package in our program we use the keyword import.
import packageName.subPackageName.className;
- There are classify packages into two types: Built–in packages and User–defined packages.
- In order to write packages we write package packageName;