A package contains Java code. It has classes, methods, and other forms of data. We import a package to use it in our program.
To begin, please create a new Java package. Call it something like testPackage
and then place a public method in the class
. The file declares itself as a package with the package keyword.
Here we see our testPackage
package. It contains a class
called Test and a printName
method. These projects are in the same directory in Eclipse.
testPackage.Test
but this is hard to type.package testPackage; public class Test { public void printName() { // This method is in the Test class in testPackage. System.out.println("Dot Net Perls"); } }import testPackage.Test; public class Program { public static void main(String[] args) { // Create new instance of Test from testPackage. Test test = new Test(); // Call method. test.printName(); } }Dot Net Perls
With a star, we can import all types in a certain package. Consider the java.util.function
package. We can import all its classes with a star directive.
import java.util.function.*;
We created a package and imported it into the default package. Importing a package simply makes it easier to access—we can use the "Test" class
directly.
With the import keyword, we can use classes like ArrayList
with simpler syntax. For ArrayList
we import java.util.ArrayList
. This makes programs easier to read.
Modularity is a key part of Java programming. Object-oriented programming is about decomposing programs into small parts that can be reused. Packages are meant to be used again and again.