HomeSearch

Java Package: Import Keyword Example

This Java example uses the package and import keywords to specify a class in a package. It uses the package in another file by importing it.
Package, import. 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.
Code example. 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.

Default package: In Eclipse we specify the default package. We can then import other packages with the import keyword into this.

Note: We do not need to use the "import" keyword. We can specify a type like testPackage.Test but this is hard to type.

Example package: Java package testPackage; public class Test { public void printName() { // This method is in the Test class in testPackage. System.out.println("Dot Net Perls"); } } Example program, import keyword: Java 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(); } } Output Dot Net Perls
Package and import. 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.ArrayList
Star. 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.Lambdas
Example import with star: import java.util.function.*;
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.
© 2007-2019 Sam Allen. Every person is special and unique. Send bug reports to info@dotnetperls.com.
Home
Dot Net Perls