In previous posts, I had used package java.util, so I thought it is very necessary to explain this topic in detail. Packages are very important part of java. I mentioned earlier we import packages to reuse classes, fields or methods from Java API or other sources.
A package is a group of related classes, interfaces, enumerations, annotations etc. and is used in order to prevent name conflicts and easy access to similar and related types (classes, interfaces, enumerations and annotations). We can also create our own packages.
To create a package, the package declaration statement should be the first line of the source code file and should be included in every source file in the package. Package name is same as the folder name in which all the compiled class files are stored. Below, I have created a package named as cards, which has 4 classes in package cards - spade, club, diamond and heart -
package cards; // Class Spade
public class spade {
// Class Spade fields and methods
}package cards; // Class Club
public class club {
// Class Club fields and methods
}package cards; // Class Diamond
public class diamond {
// Class Diamond fields and methods
}package cards; // Class Heart
public class heart {
// Class Heart fields and methods
}
To access the package cards, the following import statement should be in the first line after package statement (if there is any package) -
import cards.*;
or
import cards.spade // If you want to use particular class
Few examples of Java API packages commonly used, given below -
- java.lang
- java.util
- java.awt
- java.io
- java.time
- java.text
- java.math
NOTE: We will learn more about other packages as needed.